[R] A function as argument of another function

Martin Maechler maechler at stat.math.ethz.ch
Thu Apr 17 10:13:10 CEST 2003

>>>>> "vito" == vito muggeo <vito.muggeo at giustizia.it>
>>>>>     on Thu, 17 Apr 2003 09:45:41 +0200 writes:

(MM: I've added " " around "<-" and empty lines:)

    vito> Dear all,
    vito> I would like to write a function like:

    vito> myfun <- function(x,fn) {xx<-exp(x); x*fn(xx)}

    vito> where fn is a symbolic description of any function
    vito> with its argument to be specified. Therefore

    vito> myfun(5,"2+0.3*y^2")
    vito> should return 5*(2+0.3*exp(5)^2),

    vito> myfun(5,"log(y)") should return 5*log(exp(5)) and so on.

    vito> I tried with "expression" and others, but without
    vito> success. How can I solve my problem?

As you say yourself in the subject, the argument must be a
*function*, not a string or an expression, e.g.,  
   function(y) y^2  

is a function.  So,

  myfun <- function(x,fn) { xx <- exp(x); x*fn(xx) }
  myfun(5, function(y) 2+0.3*y^2)

gives 33049.7, as desired.

Martin Maechler <maechler at stat.math.ethz.ch>	http://stat.ethz.ch/~maechler/

More information about the R-help mailing list