问题
I am trying to build a S4 object by calling the validity method in the constructor.
setClass("Person", slot = c(Age = "numeric"))
validityPerson<-function(object){
if(object@Age < 0)return("Age cannot be negative")
TRUE
}
setValidity("Person", validityPerson)
setMethod("initialize","Person", function(.Object,...){
validObject(.Object)
.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.
回答1:
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()
validObject(.Object)
.Object
})
回答2:
setClass
actually does a lot of this work for you. If you modify your first line to capture the return:
setClass("Person", slot = c(Age = "numeric")) -> Person
then you can instantiate objects with
Person(Age=12)
.
来源:https://stackoverflow.com/questions/40024922/s4-constructor-initialize-and-prototype