[R] Understanding S4 method dispatch

Hadley Wickham h.wickham at gmail.com
Tue Aug 13 15:08:28 CEST 2013


Hi all,

Any insight into the code below would be appreciated - I don't
understand why two methods which I think should have equal distance
from the call don't.

Thanks!

Hadley

# Create simple class hierarchy
setClass("A", "NULL")
setClass("B", "A")

a <- new("A")
b <- new("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")

# These work as I expect
f(a, a)
f(b, b)

setClass("AB", contains = c("A", "B"))
ab <- new("AB")

# Why does this return B-B? Shouldn't both methods be an equal distance?
f(ab, ab)

# These both return distance 1, as I expected
extends("AB", "A", fullInfo=TRUE)@distance
extends("AB", "B", fullInfo=TRUE)@distance
# So why is signature("B", "B") closer than signature("A", "A")

-- 
Chief Scientist, RStudio
http://had.co.nz/



More information about the R-help mailing list