我有以下问题(代码如下):我有两个 S4 类,让我们用 A
和 B
来指定它们。 B
类有一个 A 类对象的列表,名为 a.list
。 A
类有一个名为test()
的方法。然后,我创建了一个类型为 A
的对象,名为 a
,以及一个类型为 B
的对象,名为 b
,然后我将 a
对象插入到 b@a.list
的列表中。
当我提取 a
对象并在其中使用 test
方法时,发生以下错误:
Error en function (classes, fdef, mtable) :
unable to find an inherited method for function "test", for signature "list"
但是我直接在a
对象中使用方法,一切正常。
知道我做错了什么吗?
提前致谢
现在,代码:
> setClass("A", representation(a="character", b="numeric"))
> a <- new("A", a="Adolfo", b = 10)
> a
An object of class "A"
Slot "a":
[1] "Adolfo"
Slot "b":
[1] 10
> print(a)
An object of class "A"
Slot "a":
[1] "Adolfo"
Slot "b":
[1] 10
> setClass("B", representation(c="character", d="numeric", a.list="list"))
> b <- new("B", c="chido", d=30, a.list=list())
> b
An object of class "B"
Slot "c":
[1] "chido"
Slot "d":
[1] 30
Slot "a.list":
list()
> b@a.list["objeto a"] <- a
> b
An object of class "B"
Slot "c":
[1] "chido"
Slot "d":
[1] 30
Slot "a.list":
$`objeto a`
An object of class "A"
Slot "a":
[1] "Adolfo"
Slot "b":
[1] 10
> setGeneric(name="test",
+ def = function(object,...) {standardGeneric("test")}
+ )
[1] "test"
> setMethod("test", "A",
+ definition=function(object,...) {
+ cat("Doing something to an A object....\n")
+ }
+ )
[1] "test"
> b@a.list[1]
$`objeto a`
An object of class "A"
Slot "a":
[1] "Adolfo"
Slot "b":
[1] 10
> test(b@a.list[1])
Error en function (classes, fdef, mtable) :
unable to find an inherited method for function "test", for signature "list"
> test(a)
Doing something to a....
>
再次感谢...
最佳答案
您必须使用双方括号提取列表的单个元素:
test(b@a.list[[1]])
如果您使用单个方括号,则索引列表的一个子集,它仍然只是一个列表,而不是 A
类:
> class(b@a.list[1])
[1] "list"
> class(b@a.list[[1]])
[1] "A"
attr(,"package")
[1] ".GlobalEnv"
关于r - S4 对象组合不当行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11973719/