【发布时间】:2013-07-22 17:08:21
【问题描述】:
如何创建将数组作为插槽的 S4 类?下面,我有一个示例类。我希望能够以这样一种方式构造,即我得到两个“人”元素,每个元素都有适当的数组成员。
下面的代码给了我以下错误:“validObject(.Object) 中的错误: 无效类“person”对象:类“person”中插槽“children”的无效对象:得到类“character”,应该是或扩展类“array”
setClass("person", representation(name="character", age="numeric", children = "array"))
setMethod(
f = "[",
signature="person",
definition=function(x,i,j,...,drop=TRUE){
initialize(x, name=x@name[i], age = x@age[i], children = x@children[i])
}
)
setMethod(f = "length", signature = "person", definition = function(x){
length(x@name)
})
setMethod(f = "dim", signature = "person", definition = function(x){
length(x@name)
})
kids1 = as.array(c("Bob", "Joe", "Mary"))
person = new("person", name="John", age=40, children = kids1)
person@children[2]
kids2 = as.array(c("Steve", "Beth", "Kim"))
people = new("person", name=c("John", "Fred"), age=c(40, 20), children = as.array(c(kids1, kids2), dim = 2))
people[1]@age
people[2]@children[1]
【问题讨论】:
-
我真的不明白你为什么要一个 Person 实例来保存几个人的定义。在这种情况下,你的类应该命名为 Persons。你知道你可以将几个 Person 实例放在一个列表中,比如 persons_list,然后使用 people_list[[i]] 访问这些实例吗?