[R] How to convert S4 class slots into data.frame or how to assign variables of type 'Date'
Ronny Wölbing
ronny.woelbing at mac.com
Fri Nov 21 21:10:37 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.
>
> A couple of tests showed that this is actually a problem of
> assigning values to data.frame column. Something like this:
>
> > slotlist$DayOfTransaction <- slot(Transaction, DateOfTransaction)
>
> would preserve the type of DateOfTransaction as 'Date'.
>
> But I don't see a way to use this assigning scheme in my method
> without using the actual slotnames and giving up a lot of flexibility.
>
> Do you have any suggestions? Is there maybe even a simple way to
> convert S4 slots into data.frames?
>
> Thanks in advance
> Ronny
>
> ______________________________________________
> 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.
Does nobody has an idea?
More information about the R-help
mailing list