[R] A function as argument of another function

Pfaff, Bernhard Bernhard.Pfaff at drkw.com
Thu Apr 17 11:31:38 CEST 2003


Dear all,
I would like to write a function like:
myfun<-function(x,fn) {xx<-exp(x); x*fn(xx)}
where fn is a symbolic description of any function with its argument to be
specified. Therefore
myfun(5,"2+0.3*y^2")
should return 5*(2+0.3*exp(5)^2),
myfun(5,"log(y)") should return 5*log(exp(5)) and so on.

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

Many thanks,
vito

hello Vito,

how about:


myfun <- function(x,fn)
  {
    xx <- exp(x)
    aux <- function(y)
      {
        eval(parse(text=fn))
      }
    x*aux(xx)
  }

myfun(5,"2+0.3*y^2")

as an alternative to Ott's answer.

HTH,
Bernhard

______________________________________________
R-help at stat.math.ethz.ch mailing list
https://www.stat.math.ethz.ch/mailman/listinfo/r-help


----------------------------------------------------------------------
If you have received this e-mail in error or wish to read our e-mail 
disclaimer statement and monitoring policy, please refer to 
http://www.drkw.com/disc/email/ or contact the sender.



More information about the R-help mailing list