【发布时间】:2018-10-01 04:05:51
【问题描述】:
我在定义数组之类的类时遇到了一些麻烦,因为它们是完全类型化的(尽可能在 R 中)。
我的例子:我想定义一个类Avector,它应该包含类A的任意数量的元素。
# Define the base class
setClass("A", representation(x = "numeric"))
# Some magic needed ????
setClass("Avector", ???)
# In the end one should be able to use it as follows:
a1 <- new("A", x = 1)
a2 <- new("A", x = 2)
X <- new("Avector", c(a1, a2))
我知道在 R 中不可能有一个对象向量。所以我猜它会存储在一种“类型化”列表中。 我找到了一些解决方案,但我对此并不满意:
# Define the vectorized class
setClass(
"Avector",
representation(X = "list"),
valididty = function(.Object)) {
if (all(sapply(.Object@X, function(x) class(x) == "A")))
TRUE
else
"'Avector' must be a list of elements in the class 'A'"
}
)
# Define a method to subscript the elements inside of the vector
setMethod(
"[", signature(x = "Avector", i = "ANY", j = "ANY"),
function(x, i, j, ...) x@X[[i]]
)
# Test the class
a1 <- new("A", x = 1)
a2 <- new("A", x = 2)
avec <- new("Avector", X = list(a1, a2))
# Retrieve the element in index i
avec[i]
这种方法对我来说更像是一种 hack。有没有办法在 R 中以规范的方式做到这一点,而无需手动进行这种类型检查和索引方法?
编辑:
如果类A 不是由原子槽组成,这也应该成立。例如在这种情况下:
setClass("A", representation(x = "data.frame"))
我很高兴得到帮助 :) 干杯, 阿德里安
【问题讨论】: