[R] S4 dispatch ambiguity

Xiongtao Dai x|ongt@oxd @end|ng |rom gm@||@com
Wed Sep 21 01:04:55 CEST 2022

I am trying to make sense why the following does *not* result in 
ambiguous method selection and thus a warning:

 > setClass("A", slots=c(a  = "numeric"))
 > setClass("B", slots=c(b  = "numeric"))
 > setClass("AB", contains=c("A", "B"))
 > setGeneric("myg", function(object) standardGeneric("myg"))
[1] "myg"
 > setMethod("myg", "A", function(object) 1)
 > setMethod("myg", "B", function(object) 2)
 > ab <- new("AB", a=1, b=2)
 > myg(ab)
[1] 1

On the other hand, the following code gives me a warning

 > setMethod("+", c("A", "B"), function(e1, e2) 1)
 > setMethod("+", c("B", "A"), function(e1, e2) 2)
 > ab+ab
Note: method with signature ‘A#B’ chosen for function ‘+’,
  target signature ‘AB#AB’.
  "B#A" would also be valid
[1] 1

It appears that S4 is using the order of the superclasses A and B for 
dispatching, and that this is not regarded as an ambiguity. Is this the 
expected behavior? I am using R 4.2.1.

It seems this is contradictory to what the documentation of 
methods::setMethod says: "The first possible source of ambiguity arises 
if the class has several direct superclasses and methods have been 
defined for more than one of those; R will consider these equally valid 
and report an ambiguous choice."


More information about the R-help mailing list