[R] multiple versions of function

William Dunlap wdunlap at tibco.com
Thu Jan 10 17:13:04 CET 2013


You could make your 'f' a generic function and define methods
for various types.  E.g., using S3 generics, define
   f <- function(a, b) UseMethod("f")
   f.default <- function(a, b) 10 * a + b
   f.data.frame <- function(df) f(df$a, df$b)
and use them as
  > f(b=5:7, a=1:3)
  [1] 15 26 37
  > f(1:3, 5:7)
  [1] 15 26 37
  > d <- data.frame(b=5:7, a=1:3)
  > f(d)
  [1] 15 26 37

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf
> Of ivo welch
> Sent: Wednesday, January 09, 2013 1:00 PM
> To: David Winsemius
> Cc: r-help
> Subject: Re: [R] multiple versions of function
> 
> mea culpa.
> 
> f <- function(...) {
>   ## parse out the arguments and then do something with them
> }
> 
> ## all of these should result in the same actions
> f(2,3)  ## interprets a to be first and b to be second
> f(a=2,b=3)
> f(b=3,a=2)
> f(data.frame(a=2,b=3))
> f(data.frame(b=3,a=1))
> 
> 
> 
> On Tue, Jan 8, 2013 at 8:00 AM, David Winsemius <dwinsemius at comcast.net> wrote:
> >
> > On Jan 7, 2013, at 6:58 PM, ivo welch wrote:
> >
> >> hi david---can you give just a little more of an example?  the
> >> function should work with call by order, call by name, and data frame
> >> whose columns are the names.  /iaw
> >>
> >
> > It is I who should be expecting you to provide an example.
> >
> > -- David.
> >
> 
> ______________________________________________
> 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