[R] A function as argument of another function
Ott Toomet
otoomet at econ.dk
Thu Apr 17 10:02:12 CEST 2003
Pronto,
It is very easy. You have to define your fn as a function:
myfun < function(x,fn) {xx<exp(x); x*fn(xx)}
testf < function(y) 2 + 0.3*y^2
myfun(5, testf)
or you may write
myfun(5, function(y) 2 + 0.3*y^2)
In your example you passed a character string into the function, I am
pretty sure it can be transformed into function but you don't need to.
Cheers,
Ott
 From: "vito muggeo" <vito.muggeo at giustizia.it>
 Date: Thu, 17 Apr 2003 09:45:41 +0200

 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?
More information about the Rhelp
mailing list