Question

I have the following problem (the code is below): I have two S4 classes, lets designate them by A and B. The B class has a list of A-type objects, named a.list. The A class has a method named test(). Then, I create a object of type A, called a, and an object of type B, b, then I insert the a object in the list of b@a.list.

When I extract the a object and use in it the testmethod the following error happens:

Error en function (classes, fdef, mtable)  : 
  unable to find an inherited method for function "test", for signature "list"

But I use the method directly in the a object, everything works normally.

Any idea what I am doing wrong?

Thanks in advance

And now, the code:

> 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....
> 

Thanks again...

Was it helpful?

Solution

You must extract single elements of a list using double square brackets:

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

If you use single square brackets you index a subset of a list, which is still just a list, and not of class A:

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

> class(b@a.list[[1]])
[1] "A"
attr(,"package")
[1] ".GlobalEnv"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top