Dan Murphy
2012-Jan-23 15:07 UTC
[Rd] factor S4 class is NA when as.character method exists
Hello, 'factor' returns <NA> for my S4 object when the class is given an "as.character" method. Here is a minimal example:> setClass("foo", contains="numeric") > bar <- new("foo", 12) > factor(bar)[1] 12 Levels: 12> setMethod("as.character", "foo", function(x) paste("x=", x@.Data))[1] "as.character"> as.character(bar)[1] "x= 12"> factor(bar)[1] <NA> Levels: 12 I would like to 'aggregate' by my S4 objects, but 'factor' seems to be getting in the way. Is there an 'as.character' implementation that works better for S4 classes? I searched help.search("factor S4 class") and help.search("factor S4 as.character") without success. Thank you. Dan Murphy [[alternative HTML version deleted]]
peter dalgaard
2012-Jan-23 16:25 UTC
[Rd] factor S4 class is NA when as.character method exists
On Jan 23, 2012, at 16:07 , Dan Murphy wrote:> Hello, > > 'factor' returns <NA> for my S4 object when the class is given an > "as.character" method. Here is a minimal example: > >> setClass("foo", contains="numeric") >> bar <- new("foo", 12) >> factor(bar) > [1] 12 > Levels: 12 >> setMethod("as.character", "foo", function(x) paste("x=", x at .Data)) > [1] "as.character" >> as.character(bar) > [1] "x= 12" >> factor(bar) > [1] <NA> > Levels: 12 > > I would like to 'aggregate' by my S4 objects, but 'factor' seems to be > getting in the way. Is there an 'as.character' implementation that works > better for S4 classes? I searched help.search("factor S4 class") and > help.search("factor S4 as.character") without success.Single-stepping the factor call would have shown you that the real problem is that you don't have a unique() method for your class:> unique(bar)[1] 12 i.e., you are getting the default numeric method, which returns a numeric vector, so the levels become as.character(unique(bar)) which is c("12") and doesn't match any of the values of as.character(bar). So, either provide a unique() method, or use factor(as.character(bar)).> > Thank you. > > Dan Murphy > > [[alternative HTML version deleted]] > > ______________________________________________ > R-devel at r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-devel-- Peter Dalgaard, Professor Center for Statistics, Copenhagen Business School Solbjerg Plads 3, 2000 Frederiksberg, Denmark Phone: (+45)38153501 Email: pd.mes at cbs.dk Priv: PDalgd at gmail.com