2012-08-15 46 views
3

我有以下问题(代码如下):我有两个S4类,可以通过AB指定它们。 B类具有一个名为a.list的A型对象列表。 A类有一个名为test()的方法。然后,我创建了一个类型为A的对象,名为a,并且该对象的类型为B,b,然后我将a对象插入到[email protected]的列表中。S4对象组成不当行为?

当我提取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() 

> [email protected]["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" 
> [email protected][1] 
$`objeto a` 
An object of class "A" 
Slot "a": 
[1] "Adolfo" 

Slot "b": 
[1] 10 

> test([email protected][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.... 
> 

谢谢...

回答

6

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

test([email protected][[1]]) 

如果您使用单个方括号索引列表的子集,这是stil我只是一个列表,而不是类A

> class([email protected][1]) 
[1] "list" 

> class([email protected][[1]]) 
[1] "A" 
attr(,"package") 
[1] ".GlobalEnv" 
+0

哇!这是快速而精确的! 谢谢! +1以上所有! – nanounanue 2012-08-15 17:17:00