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

Ronny Wölbing ronny.woelbing at me.com
Thu Nov 20 11:32:29 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



More information about the R-help mailing list