如何禁止S4对象的空插槽?

时间:2016-11-18 10:27:58

标签: r s4

假设我的课程定义如下:

setClass("myclass", slots = list(id="character"))

我希望事情是这样的,id是必需的,myclass没有id是无效的对象。目前,我得到以下内容:

> new("myclass")
An object of class "myclass"
Slot "id":
character(0)

我希望设置验证功能会有所帮助:

setValidity("myclass", function(object){
  if(length(slot(object, "id")) == 0L){
    return("You cannot do that")
  }
  return(TRUE)
})

> new("myclass")
An object of class "myclass"
Slot "id":
character(0)

但不幸的是,似乎有空参数会导致验证函数被绕过。有没有办法让这种输入无效?

1 个答案:

答案 0 :(得分:0)

我能找到的最佳解决方案是将验证步骤放在构造函数中(这对我来说似乎有点不合适):<​​/ p>

setMethod("initialize", "myclass", function(.Object, id){
  if(missing(id)) stop("The id is not allowed to be empty")
  .Object@id <- id
  validObject(.Object)
  return(.Object)
})

这现在给出了预期的结果:

> new("myclass")
Error in .local(.Object, ...) : The id is not allowed to be empty
> new("myclass", id = character())
Error in validObject(.Object) : 
  invalid class “myclass” object: You cannot do that
> new("myclass", id = "a")
An object of class "myclass"
Slot "id":
[1] "a"