modestprog
modestprog

Reputation: 73

In R how to define a method with the same name in different S4 classes for a correct method dispatching

I've defined a method called "getValues" for a new S4 class in R. My class and method are:

myClass<-setClass("MyClass", 
                  slots=list(a="numeric",b="list"))

setMethod("getValues", signature ( "MyClass", "missing", "missing"),
          getValues<-function(x)
          {
            print("MyClass-getValues called")
          })

The 'raster' package already has a method called 'getValues' but with different signatures (can be seen with showMethods("getValues")). So I thought method dispatching will select the correct method depending of the signature. But when I run:

a<-raster()
getValues(a)  #problem: this calls "getValues" of the class 'MyClass' and prints "MyClass-getValues called"

I expected that the 'getValues' method for RasterLayer objects will be called, but this calls "getValues" of the class 'MyClass'!

Where is the error?

Upvotes: 0

Views: 167

Answers (1)

JDL
JDL

Reputation: 1654

The error is in the commented line below:

myClass<-setClass("MyClass", 
                  slots=list(a="numeric",b="list"))

setMethod("getValues", signature ( "MyClass", "missing", "missing"),
          ##getValues<-function(x)##
          {
            print("MyClass-getValues called")
          })

This line overwrites the main definition of getValues as well as setting a method. Call this function anything other than getValues and it should work.

Upvotes: 1

Related Questions