[R] Generic Function
ggrothendieck at myway.com
Tue Nov 4 02:04:29 CET 2003
Here is a simple example using S3 classes. We define a generic
function myday. It dispaches, i.e. calls, a function whose name
is myday followed by a dot followed by the class of the
first argument to myday. After defining myday, define two
functions for it to dispatch: myday.POSIXct and myday.numeric.
# generic function
myday <- function(x, ...) UseMethod("myday")
# if first argument is of class POSIXct then UseMethod calls this:
myday.POSIXct <- function(dat) as.POSIXlt(dat)$mday
# if first argument is of class numeric then UseMethod calls this:
myday.numeric <- function(x) x
# Here is how it would be called:
myday(20) # causes myday.numeric to be dispached. Returns 20.
myday(Sys.time()) # myday.POSIXct dispatched. Returns 3 on Nov 3rd.
# We can also query what methods are available:
methods(myday) # returns vector c("myday.POSIXct","myday.numeric")
Date: 03 Nov 2003 17:28:22 -0500
From: Arend P. van der Veen <apv at capital.net>
To: <R-Help at stat.math.ethz.ch>
Subject: [R] Generic Function
How to I write a generate function that is "specific to the class of the
argument itself" ?
For example, I created a data.frame that contains results of an
analysis. I would like to write a special plot function with the
I have been looking through the documentation but have not found
anything to show me how to do this. Any help would be greatly
Thanks in advance,
Arend van der Veen
No banners. No pop-ups. No kidding.
Introducing My Way - http://www.myway.com
More information about the R-help