[R-pkg-devel] [External] Re: Farming out methods to other packages

Duncan Murdoch murdoch@dunc@n @end|ng |rom gm@||@com
Sat Aug 10 21:42:32 CEST 2019

On 10/08/2019 3:27 p.m., Lenth, Russell V wrote:
> Hmmmm, I thought of an approach -- a kind of manual dispatch technique. My generic is
> recover_data <- function(object, ...) {
>      rd <- try(getS3method("recover_data", class(object)[1], envir = .GlobalEnv, silent = TRUE))
>      if (!inherits(rd, "try-error"))
>          rd(object, ...)
>      else
>          UseMethod("recover_data")
> }
> and similar for emm_basis. The idea is it tries to find the method among globally registered ones, and if so, it uses it; otherwise, the internal one is used.

That's a bad test:  class(object) might be a vector c("nomethod", 
"hasmethod").  You're only looking for recover_data.nomethod, and maybe 
only recover_data.hasmethod exists.

The getS3method() function won't automatically iterate through the 
class, you'll need to do that yourself, for example

S3methodOrDefault <- function(object, generic, default) {
   for (c in class(object)) {
     rd <- try(getS3method(generic, c, envir = .GlobalEnv, silent = TRUE))
     if (!inherits(rd, "try-error"))

used as

   S3methodOrDefault(object, "recover_data", internal_recover_data)

Duncan Murdoch

More information about the R-package-devel mailing list