In R, we can convert an S4 object into a data frame by defining a new method for the generic function as.data.frame
. This method will specify how the S4 object should be converted to a data frame.
Here's an example with an S4 object defined using the setClass
function:
main.r462 chars18 lines
In this example, we first defined an S4 class called Person
with two slots: name
and age
. Then, we created an object of this class called person
.
Next, we defined a new method for the as.data.frame
function specifically for objects of the Person
class. This method extracts the name
and age
slots from the S4 object and creates a data frame with these values.
Finally, we applied the new as.data.frame
method to person
, which converted the S4 object to a data frame with two columns: name
and age
.
gistlibby LogSnag