[Rd] setIs and method dispatch in S4 classes

Peter Ruckdeschel Peter.Ruckdeschel at uni-bayreuth.de
Fri Apr 7 12:12:32 CEST 2006


Dear all,

I have a question regarding setIs and method dispatch in S4 classes:
Consider the following example:
#####################################################
## A02 "contains" A01 by setIs:
setClass("A01", representation(a="numeric",b="numeric"))
setClass("A02", representation(a="numeric",d="numeric"))
setIs("A02","A01",coerce=function(obj){new("A01", a=obj at a, b=obj at d)},
       replace=function(obj,value){new("A01", a=value at a, b=value at b)})

#only a "+" method  for A01
setMethod("+", signature=c("A01","A01"), function(e1,e2){e1 at b+e2@b})

x1=new("A02", a=1, d=2)
x2=new("A02", a=1, d=3)

x1+x2 ## 5 as expected

## now: B00 mother class to B01 and B02, and again B02 "contains" B01 by
setIs:
setClass("B00", representation(a="numeric"))
setClass("B01", representation(a="numeric",b="numeric"), contains= "B00")
setClass("B02", representation(a="numeric",d="numeric"), contains= "B00")
setIs("B02","B01",coerce=function(obj){new("B01", a=obj at a, b=obj at d)},
       replace=function(obj,value){new("B01", a=value at a, b=value at b)})

# now two "+" methods  for B00 and B01
setMethod("+", signature=c("B00","B00"), function(e1,e2){e1 at a+e2@a})
setMethod("+", signature=c("B01","B01"), function(e1,e2){e1 at b+e2@b})

x1=new("B02", a=1, d=2)
x2=new("B02", a=1, d=3)

x1+x2 ## 2 --- why?
#####################################################
    (tested on  2.3.0 alpha (2006-04-05 r37653))

I would have guessed that this again would give 5, as B02 is deeper
in the class hierarchy than B00 and the calls to setIs specifies an
unconditional
is-relation.

What is the principle then behind this dispatching mechanism?

Is there a possibility to force usage of the B01 method /without/
explicitely coercing x1,x2 to B01, i.e. interfere in the dispatching 
precedence, telling R somehow  (by particular arguments for setIs ?)  
to always use the is-relation defined by setIs first before mounting 
the hierarchy tree?

Thank you for your attention
Peter



More information about the R-devel mailing list