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

From: Mark Lyman <mark.lyman_at_atk.com>
Date: Fri, 21 Nov 2008 21:23:05 +0000 (UTC)

> > 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



R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Fri 21 Nov 2008 - 21:26:23 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Fri 21 Nov 2008 - 21:30:28 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive