Skip to content
Prev 15888 / 63461 Next

Overloading methods in R

On 4/21/05, Ali - <saveez@hotmail.com> wrote:
Here is another example which hopefully shows that
there is no limitation on number of arguments,
number of methods and classes.    Here we have
methods with one, two and three arguments and a
variety of classes.

Note that this and the previous examples are not
intended to be complete finished solutions to your
problem but are only illustrative to give you the
idea how to proceed.  Generalizing them should not
be too complex nor inelegant.  Dealing with
vectors of arguments is not that much harder than
dealing with individual arguments in a vector
oriented language like R.


f <- function(...) UseMethod("f", NULL)

f.NULL <- function(...) {
	args <- list(...)
	classes <- sapply(args, class)
	.Class <- paste(classes, collapse = ".")
	NextMethod("f", ...)
}

f.numeric <- function(...) 2 * ..1 
f.numeric.numeric <- function(...) ..1 + ..2
f.character.numeric.Date <- function(...) {
   args <- list(...)
   paste(args[[1]], args[[2]], format(args[[3]], "%Y-%m-%d"))
}
f.default <- function(...) print(list(...))


f(1)   # 2
f(1,2) # 3
f("a", 23, Sys.Date()) # "a 23 2005-04-21"
f()    # list()