我有以下问题(代码如下):我有两个S4类,可以通过A
和B
来指定它们。 B
类有一个名为a.list
的A类对象列表。 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....
>
再次感谢...
答案 0 :(得分:6)
您必须使用双方括号提取列表的单个元素:
test(b@a.list[[1]])
如果使用单方括号,则索引列表的子集,该列表仍然只是列表,而不是类A
:
> class(b@a.list[1])
[1] "list"
> class(b@a.list[[1]])
[1] "A"
attr(,"package")
[1] ".GlobalEnv"