[R] Understanding S4 method dispatch

Simon Zehnder szehnder at uni-bonn.de
Wed Aug 14 18:36:10 CEST 2013


Because the signature is always (A,A) or (B,B). Then, as in AB we have A and B and no relationship between A and B, R chooses the method lexicographically. The result is as expected: f for A is chosen. 

If you would do something like: 

setClass("A", contains = "list")
setClass("B", contains = "list")
setClass("AB", contains = c("A", "B"))

setGeneric("f", function(x, y) standardGeneric("f"))
setMethod("f", signature("A", "ANY"), function(x, y) "A-ANY")
setMethod("f", signature("ANY", "A"), function(x, y) "ANY-A")
setMethod("f", signature("B", "B"), function(x, y) "B-B")

ab <- new("AB")
f(ab, ab)

You get an ambiguity, as there is no function with signature pair that can be directly matched for A. But for B such a signature pair exists. So R chooses B. If you would specify again a function for signature (A,A) we are back:

setMethod("f", signature("A", "A"), function(x, y) "A-A")
f(ab, ab)


Best 

Simon


On Aug 14, 2013, at 5:25 PM, Hadley Wickham <h.wickham at gmail.com> wrote:

>> In my opinion the reason for the behavior lies in the specific multiple inheritance structure between AB, B and A.
> 
> So what if we don't make such a weird inheritance structure, and
> instead have A and B inherit from a common parent:
> 
> setClass("A", contains = "list")
> setClass("B", contains = "list")
> setClass("AB", contains = c("A", "B"))
> 
> setGeneric("f", function(x, y) standardGeneric("f"))
> setMethod("f", signature("A", "A"), function(x, y) "A-A")
> setMethod("f", signature("B", "B"), function(x, y) "B-B")
> 
> ab <- new("AB")
> f(ab, ab)
> 
> Why isn't there a warning about ambiguous dispatch?
> 
> Hadley
> 
> -- 
> Chief Scientist, RStudio
> http://had.co.nz/



More information about the R-help mailing list