[R] How to convert S4 class slots into data.frame or how to assign variables of type 'Date'

Mark Lyman mark.lyman at atk.com
Fri Nov 21 22:23:05 CET 2008


> > Hi,
> >
> > I created a class (S4) with some slots like value, date, description  
> > (it's actually a financial transaction class). Now  I need a method  
> > to convert this class forth and back into a single row data.frame,  
> > where every slots represents a column. This method looks at the  
> > moment like this:
> >
> > > setMethod("as.data.frame", "Transaction",
> >        function(x, row.names = NULL,  optional = FALSE, ...){
> >                        slotnames <- slotNames(x)
> >                        slotlist <-  
> > data.frame(rbind(1:length(slotnames)))
> >                        names(slotlist) <- slotnames
> >                        for(i in slotnames) {
> >                                    slotlist[1, i] <- slot(x,  i)
> >                        }
> >                        return(slotlist)
> >                    }
> > )
> >
> > This method doesn't require predetermined slotnames or types, which  
> > is important to me. The method works quite good but the problem is  
> > that I have slots of type 'Date' and this method doesn't preserve  
> > the type but converts it to numeric.
> >


You would probably have gotten a quicker response if you had made a 
reproducible example as requested in the posting guide. However, the following 
example should give you a solution.

tmp <- new("numWithId", 1, id = Sys.Date())
slotnames <- slotNames(tmp)
slotlist <- vector("list", length(slotnames))
names(slotlist) <- slotnames
for(i in slotnames) slotlist[[i]] <- slot(tmp, i)
as.data.frame(slotlist)

Take a look at the coercion section of ?"[.data.frame". I belive your Date is 
being converted to numeric to match the class of what it is replacing.

Mark Lyman
Statistician, ATK



More information about the R-help mailing list