我正在尝试为S4类编写子集化方法。无论我怎么做,都会出现this S4 class is not subsettable
错误。
这是一个最小的例子:
setClass(Class = "A", representation = representation(ID = "character"))
setClass(Class = "B", representation = representation(IDnos = "list"))
a1 <- new(Class = "A", ID = "id1")
a2 <- new(Class = "A", ID = "id2")
B1 <- new(Class = "B", IDnos = c(a1, a2))
当我输入:
B1@IDnos[[1]]
我得到了我想要的东西:
> An object of class "A" > Slot "ID": > [1] "id1"
但是我想通过写B1[1]
或者B1[[1]]
从THIS帖子,我有了一些想法,并试图模仿作者写的内容。但它在我的情况下不起作用:
setMethod("[", c("B", "integer", "missing", "ANY"),
function(x, i, j, ..., drop=TRUE)
{
x@IDnos[[i]]
# initialize(x, IDnos=x@IDnos[[i]]) # This did not work either
})
B1[1]
> Error in B1[1] : object of type 'S4' is not subsettable
以下代码也不起作用:
setMethod("[[", c("B", "integer", "missing"),
function(x, i, j, ...)
{
x@IDnos[[i]]
})
B1[[1]]
> Error in B1[[1]] : this S4 class is not subsettable
有什么想法吗?
答案 0 :(得分:8)
我认为你的问题是你的签名过于严格。你需要一个&#34;整数&#34;类。默认情况下
class(1)
# [1] "numeric"
所以它实际上并不是真正的整数&#34;数据类型。但是当你确实指定一个整数文字
时class(1L)
# [1] "integer"
B1[1L]
# An object of class "A"
# Slot "ID":
# [1] "id1"
因此,使用更通用的
签名可能会更好setMethod("[", c("B", "numeric", "missing", "ANY"), ... )
这将允许您的原始尝试工作
B1[2]
# An object of class "A"
# Slot "ID":
# [1] "id2"