[R] S4 dispatch ambiguity

Andrew Simmons @kw@|mmo @end|ng |rom gm@||@com
Wed Sep 21 21:55:55 CEST 2022


In the first scenario, your object is class AB, then class A with distance
1, then class B with distance 2. This means that method A is preferable
since it is less distance away than method B.

However, in your second function, both methods are a total distance of 3
away, so (as far as I know) it chooses the first choice in the list and
raises a warning that both are acceptable.

Using contains = c("A", "B") as an ordered set of classes is intended. The
same is true of other multi-inheritance languages, such as python.

I had a similar problem when I was defining methods myself, I had something
like:

row.match <- function (x, table, ...) {}
setGeneric(row.match)
setMethod(row.match, c("data.frame", "ANY"), ...)
setMethod(row.match, c("ANY", "data.frame"), ...)

The easiest thing to do is the define another method like this:
setMethod(row.match, c("data.frame", "data.frame"), ...)

And that removes the ambiguity. For your scenario, I would define two
methods like:
setMethod(`+`, c("A", "A"), ...)
setMethod(`+`, c("B", "B"), ...)

and that should remove your ambiguity.

On Wed., Sep. 21, 2022, 12:06 Xiongtao Dai, <xiongtaoxd using gmail.com> wrote:

> 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."
>
> Best,
> Xiongtao
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

	[[alternative HTML version deleted]]



More information about the R-help mailing list