2012-08-15 52 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