R S4类不可再附加
我正在尝试为S4类编写一个子集设置方法。我得到R S4类不可再附加,r,s4,R,S4,我正在尝试为S4类编写一个子集设置方法。我得到这个S4类是不可子集的错误,无论我尝试了什么 下面是一个简单的例子: setClass(Class = "A", representation = representation(ID = "character")) setClass(Class = "B", representation = representation(IDnos = "list")) a1 <- new(Class = "A", ID = "id1") a2 <-
这个S4类是不可子集的
错误,无论我尝试了什么
下面是一个简单的例子:
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[1]
或者如果不是通过B1[[1]]
从这篇文章中,我得到了一些想法,并试图模仿作者写的东西。但在我的情况下,它不起作用:
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
有什么想法吗?我想你的问题是你的签名太严格了。您需要一个“整数”类。默认情况下
class(1)
# [1] "numeric"
所以它实际上不是一个真正的“整数”data.type。但当您实际指定一个整数文本时
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"
抢手货工作得很好。非常感谢。
setMethod("[", c("B", "numeric", "missing", "ANY"), ... )
B1[2]
# An object of class "A"
# Slot "ID":
# [1] "id2"