mth_mad mth_mad - 13 days ago 4
R Question

S4 constructor initialize and prototype

I am trying to build a S4 object by calling the validity method in the constructor.

setClass("Person", slot = c(Age = "numeric"))

if(object@Age < 0)return("Age cannot be negative")
setValidity("Person", validityPerson)
setMethod("initialize","Person", function(.Object,...){

This code is problematic because I get

new("Person", Age = 12)
#Error in if (object@Age < 0) return("Age cannot be negative") :
#argument is of length zero

Of course I would like the Age to be equal to 12. This is a toy example, but I am trying to understand how I can have an initialize method that potentially can do all sort of other initialisations and then check that it is valid.


From the example on the ?initialize help page, you need to actually initialize the object otherwise none of the slots will be filled. Otherwise those ... are just gobbling up the parameters and not doing anything with them. You can invoke the default initialize with callNextMethod

setMethod("initialize", "Person", function(.Object, ...) {
    .Object <- callNextMethod()