R S4插槽作为自定义类的列表

R S4插槽作为自定义类的列表,r,s4,R,S4,S4类中的插槽是否可能是其他自定义类型的列表?像 setClass("customClass", representation(list(anotherCustomClass) ) 对于那些寻找答案的人来说。不,没有办法限制S4中的列表具有特定类型的元素。这实际上是有道理的,因为R中的列表被设计为包含任何类型的元素,所以为什么S4上的列表应该是不同的?这里是使用S4的类型化列表的一个相当简单的实现。检查所有对象是否为指定类型,以及所有这些对象是否为该类型的有效对象 ins

S4类中的插槽是否可能是其他自定义类型的列表?像

setClass("customClass", 
          representation(list(anotherCustomClass)
)

对于那些寻找答案的人来说。不,没有办法限制S4中的列表具有特定类型的元素。这实际上是有道理的,因为R中的列表被设计为包含任何类型的元素,所以为什么S4上的列表应该是不同的?

这里是使用S4的类型化列表的一个相当简单的实现。检查所有对象是否为指定类型,以及所有这些对象是否为该类型的有效对象

instanceof = function(object, type) {
  class(object)[[1]] == type
}

typed_list_check = function(object) {

  errors = character()
  is_correct_object_type = logical()

  if (length(object@objects) >= 1) {
    for (i in 1:length(object@objects)) {
      obj = object@objects[[i]]
      is_correct_object_type[[i]] = instanceof(obj, object@type)
    }

    if (any(!is_correct_object_type)) {
      msg = sprintf("At least one object is not of type %s.", object@type)
      errors = c(errors, msg)
    }

    if (all(is_correct_object_type)) {
      for (obj in object@objects) {
        potential_msg = validObject(obj)
        if (is.character(potential_msg)) {
          msg = potential_msg
          errors = c(errors, msg)
        }
      }
    }
  }

  if (length(errors) == 0) TRUE else errors
}

setClass(
  "TypedList",
  representation(
    type = "character",
    objects = "list"
  ),
  validity = typed_list_check
)

我认为您只需要有
表示(list)
,就可以存储列表中的任何内容,包括您的
另一个CustomClass
。您可以在
set
方法中检查要存储的对象的类…?@Arun-是的,我已经考虑过了,同时指定了对validity方法的此类限制。我只是在寻找一些S4支持来强制执行该约束。