【问题标题】:How can I disallow empty slots for S4 objects?如何禁止 S4 对象使用空插槽?
【发布时间】:2016-11-18 10:27:58
【问题描述】:

假设我有一个定义如下的类:

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

我希望 id 是强制性的,而没有 id 的 myclass 是无效对象。目前,我得到以下信息:

> 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)

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

【问题讨论】:

    标签: r s4


    【解决方案1】:

    我能找到的最佳解决方案是将验证步骤放在构造函数中(这对我来说似乎有点反常):

    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"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-17
      • 1970-01-01
      • 2015-06-11
      • 1970-01-01
      • 2016-06-09
      • 2011-11-14
      • 1970-01-01
      • 2015-05-21
      相关资源
      最近更新 更多