mth_mad mth_mad - 5 months ago 48
R Question

R Instance of S4 object with S3 attribute

I am currently creating a new S4 class which uses a S3 zoo object. I can create a class

setClass("rollingSD", slot = c(rollPeriod = "numeric", tsOutput = "zoo"))

This code works fine. Now if I want to create an object as

riskSD <- new("rollingSD")

This also works fine. However, the following generates an error

riskSD <- new("rollingSD", rollPeriod = 12)
Error in validObject(.Object) :
invalid class “rollingSD” object: invalid object for slot "tsOutput" in class
"rollingSD": got class "S4", should be or extend class "zoo"

This not clear for me why a default object of the zoo class is not inititated. I also do not know how to fix this.


The problem is caused because R's class mechanism doesn't know how to make a new zoo object. You can fix this by specifying a "prototype":

  slot = c(rollPeriod = "numeric", tsOutput = "zoo"),

where some_zoo_object is of class zoo. The default prototype for a numeric slot is numeric(), but because you defined the (S4) class zoo yourself, the default is new("zoo") and this isn't defined.