3

我有以下问题(代码如下):我有两个 S4 类,让我们用A和指定它们B。该类B有一个 A 型对象列表,名为a.list. 该类A有一个名为 的方法test()。然后,我创建一个类型为 的对象A,称为a,和一个类型为 的对象Bb然后我将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....
> 

再次感谢...

4

1 回答 1

6

您必须使用双方括号提取列表的单个元素:

 test(b@a.list[[1]])

如果您使用单方括号,则索引列表的子集,它仍然只是一个列表,而不是 class A

> class(b@a.list[1])
[1] "list"

> class(b@a.list[[1]])
[1] "A"
attr(,"package")
[1] ".GlobalEnv"
于 2012-08-15T17:12:12.470 回答