S4 constructor initialize and prototype

二次信任 提交于 2019-12-25 14:11:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!