I want to create data.frame of various variables, including S4 classes. For an inline class such as "POSIXlt" (for dates), this works fine:
as.data.frame(list(id=c(1,2), date=c(as.POSIXlt('2013-01-01'),as.POSIXlt('2013-01-02'))
But now I have a custom class, say, the class "Man" with a name and age:
setClass("person", representation(name="character", age="numeric"))
But the following is true:
as.data.frame(list(id=c(1,2), pers=c(new("person", name="John", age=20), new("person", name="Tom", age=30))))
I also tried to overload the [...] operator for the human class using
setMethod( f = "[", signature="person", definition=function(x,i,j,...,drop=TRUE){ initialize(x, name=x@name [i], age = x@age [i]) } )
This allows you to use vector behavior:
persons = new("person", name=c("John","Tom"), age=c(20,30)) p1 = persons[1]
But still the following is true:
as.data.frame(list(id=c(1,2), pers=persons))
Perhaps I have to overload more operators to get a user-defined class in a dataframe? I am sure there must be a way to do this, since POSIXlt is an S4 class and it works! Any solution using the new R5 reference classes would be great!
I don’t want to put all my data in the person class (you might ask why the "id" is not a member of the person, I just do not use dataframes)! The idea is that my data.frame file is a table from a database with many columns with different types, like rows, numbers, ... but also dates, intervals, geo objects, etc. Although I already have a solution for dates (POSIXlt), for intervals, geo objects, etc. Perhaps I need to specify my own S4 / R5 classes.
Thank you very much in advance.