[Rd] yet another problem with S4 dispatch (with setClassUnion)

Peter Ruckdeschel Peter.Ruckdeschel at uni-bayreuth.de
Wed Apr 12 13:27:52 CEST 2006

Dear John and Seth,  dear R-devels,

once again the question of method dispatch in S4 -- this time with
setClassUnion(); taking up your advice in


I have been too quick in stating that

>setClassUnion()---at least in my case---solves the problem;
The problem arises if I have a  direct superclass "competing"
with the new class generated by setClassUnion();

consider the following code:

##  C00 mother class to C01 and C02
setClass("C00", representation(a="numeric"), prototype =c(a=0))
setClass("C01", representation(a="numeric",b="numeric"), contains= "C00")
setClass("C02", representation(a="numeric",d="numeric"), contains= "C00")

#with setClassUnion:
setClassUnion("C01OrC02", c("C01","C02"))

#  "+" methods  for C00 and C01OrC02
#        that this is a function to be dispatched on two arguments is
#        not important for this example

setMethod("+", signature=c("C00","C00"), function(e1,e2){e1 at a+e2@a})
setMethod("+", signature=c("C01OrC02","C01OrC02"),
         function(e1,e2){if(is(e1,"C01")) e10 <- e1
                        #  else: explicit coercion from  C02 to C01
                        else e10 <- new("C01", a=e1 at a, b=e1 at d)
                         if(is(e2,"C01")) e20 <- e2
                         #  else: explicit coercion from  C02 to C01
                         else e20 <- new("C01", a=e2 at a, b=e2 at d)
                         e10 at b+e20@b})

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

x1+x2 ## 2, i.e. uses C00-method
# but I would like to force usage of C01OrC02-method

Here the two classes C00 and C01OrC02 are direct superclasses to
C02, which exactly reflects my application of distribution classes,
confer  https://stat.ethz.ch/pipermail/r-devel/2006-April/037190.html 

How does the dispatching mechanism decide between
these two and is there a way to change precedence?

Of course, I could implement a "+" method for C02 directly
in this case, but suppose I have much more methods for
C01 and I want to use /all/ of them for C02, and cannot
organize things so that we have the inheritance chain
C00 -> C01 -> C02.  What is the preferred way of doing

Thank you already for your attention,

More information about the R-devel mailing list