[R] S4 method dispatch: coercion of arguments with setAs defined

Renaud Gaujoux renaud at mancala.cbio.uct.ac.za
Wed Aug 5 11:10:43 CEST 2009

Hi list,

I've got a class B that contains a slot obj of class A. I'd like to be 
able to call all the methods of class A directly on objects of class B 
as if I had called the method on slot obj. This without overloading all 
methods of class A to work on class B.
I don't define B as an extension of A, because I want class B to also 
work with objects of classes that inherit from class A and that I don't 
know the names.

So I tried to dispatch the methods of class A to slot obj using function 
setAs as follows:

setClass('A', representation(number='numeric'))
setGeneric('getNumber', function(object) standardGeneric('getNumber'))
setMethod('getNumber', 'A', function(object) object at number)

setClass('B', representation(obj='A', extra='list'))
setAs('B', 'A', def= function(from) from at obj )

objB <- new('B', obj=new('A', number=10))

But get the error:

Error in function (classes, fdef, mtable)  :
  unable to find an inherited method for function "getNumber", for 
signature "B"

I thought the dispatch procedure in S4 would try to find a way to coerce 
objects of class 'B' into the closest class usable with the given method 
(in that case into an object of class 'A'). I expected it to internally do:

getNumber(as(objB, 'A'))

Am I thinking wrong or do I need to do another thing to make it work?


More information about the R-help mailing list