Combining S4 and S3 methods in a single function

前端 未结 1 1974
遥遥无期
遥遥无期 2020-12-01 12:42

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:



        
相关标签:
1条回答
  • 2020-12-01 13:46

    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.

    0 讨论(0)
提交回复
热议问题