是否可以将 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
)