[R] suggestion on method dispatch
Gabor Grothendieck
ggrothendieck at gmail.com
Tue Apr 27 17:14:16 CEST 2010
Define fn.default as a synonym to fn.foo1 (or just rename fn.foo1 as
fn.default) and then use NextMethod as shown:
fn <- function(x,...) UseMethod("fn")
fn.default <-
fn.foo1 <- function(x, commonA=1, ...) {
print("fn.foo1 is called.")
}
fn.foo2 <- function(x, uniqueFoo2, common=1, ...){
NextMethod("fn", x = uniqueFoo2)
}
y <- "y"; class(y) <- "foo2"
fn(x=y, "unique argument")
On Tue, Apr 27, 2010 at 10:40 AM, Wincent <ronggui.huang at gmail.com> wrote:
> Dear all, I have define a function and its methods as follows:
>
> ######## beginning of code
> fn <- function(x,...){
> UseMethod("fn")
> }
>
> fn.foo1 <- function(x, commonA=1, ...){
> print("fn.foo1 is called.")
> }
>
> fn.foo2 <- function(x, uniqueFoo2, common=1, ...){
> ## uniqueFoo2 is a unique argument in fn.foo2
> x <- uniqueFoo2; class(x) <- "foo1"
> ## use uniqueFoo2 to generate a object of class foo1
> dots <- list(...)
> do.call(fn.foo1, c(list(x=x,common=common),dots)
> ## pass x, commonA and other arguments from ... to fn.foo1
> }
>
> y <- "y"; class(y) <- "foo2"
> fn(x=y, "unique argument")
>
> ######## end of code
>
> They works as expected. I call fn.foo1 because I don't want to
> duplicate the same piece of code.
> Yet, I wonder if here is any official way to do the same thing without
> directly call fn.foo1 via do.call.
> To directly call a method is not a good coding style, right?
>
> Thanks very much for your suggestion in advance.
>
> --
> Wincent Rong-gui HUANG
> Doctoral Candidate
> Dept of Public and Social Administration
> City University of Hong Kong
> http://asrr.r-forge.r-project.org/rghuang.html
>
> ______________________________________________
> R-help at r-project.org mailing list
> 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.
>
More information about the R-help
mailing list