Combining S4 and S3 methods in a single function

2020-01-29 07:31发布

What is a good way of defining a general purpose function which should have implementations for both S3 and S4 classes? I have been using something like this:

setGeneric("myfun", function(x, ...){  
    standardGeneric("myfun");
});

setMethod("myfun", "ANY", function(x, ...) {
    if(!isS4(x)) {
        return(UseMethod("myfun"));
    }
    stop("No implementation found for class: ", class(x));
});

This succeeds:

myfun.bar <- function(x, ...){
    return("Object of class bar successfully dispatched.");
}
object <- structure(123, class=c("foo", "bar"));
myfun(object)

Is there a move "native" way to accomplish this? I know we can define S4 methods for S3 classes using setOldClass, however this way we lose the S3 method dispatching in case an object has multiple classes. E.g. (in a clean session):

setGeneric("myfun", function(x, ...){  
    standardGeneric("myfun");
});

setOldClass("bar")
setMethod("myfun", "bar", function(x, ...){
    return("Object of class bar successfully dispatched.");
});

object <- structure(123, class=c("foo", "bar"));
myfun(object)

This fails because the second class of object, in this case bar, is ignored. We could probably fix this by defining formal S4 inheritance between foo and bar, but for my application I would rather want myfun.bar to work out of the box on S3 objects with a class bar.

Either way, things are getting messy, and I guess this is a common problem, so there are probably better ways to do this?

标签: r cran s4
1条回答
你好瞎i
2楼-- · 2020-01-29 08:07

The section "Methods for S3 Generic Functions" of ?Methods suggest an S3 generic, an S3-style method for S4 classes, and the S4 method itself.

setClass("A")                    # define a class

f3 <- function(x, ...)           # S3 generic, for S3 dispatch    
    UseMethod("f3")
setGeneric("f3")                 # S4 generic, for S4 dispatch, default is S3 generic
f3.A <- function(x, ...) {}      # S3 method for S4 class
setMethod("f3", "A", f3.A)       # S4 method for S4 class

The S3 generic is needed to dispatch S3 classes.

The setGeneric() sets the f3 (i.e., the S3 generic) as the default, and f3,ANY-method is actually the S3 generic. Since 'ANY' is at (sort of) the root of the class hierarchy, any object (e.g., S3 objects) for which an S4 method does not exist ends up at the S3 generic.

The definition of an S3 generic for an S4 class is described on the help page ?Methods. I think, approximately, that S3 doesn't know about S4 methods, so if one invokes the S3 generic (e.g., because one is in a package name space where the package knows about the S3 f3 but not the S4 f3) the f3 generic would not find the S4 method. I'm only the messenger.

查看更多
登录 后发表回答