Robin Hankin wrote:
>>I've just begun writing a program that searches for the minimum of a
>>function with golden section search. In order to do this in a nice way
>>I
>>need a function that takes a function name and an argument and returns
>>the
>>function value for that argument, i .e just like Matlab's 'feval'. Is
>>there any?
It might be better to write a function that takes a function as an
argument, instead of the function name:
> doit = function(f,...){f(...)}
> doit(sqrt,2)
[1] 1.414214
> doit(sum,1,2,3)
[1] 6
This way you can write little inline anonymous functions:
> doit(function(a,b,c){a^3+b^2+c},1,4,3)
[1] 20
The equivalent way with do.call, and function names is:
> docall=function(fc,...){do.call(fc,list(...))}
> docall("sqrt",2)
[1] 1.414214
> docall("sum",1,2,3)
[1] 6
But:
> docall("function(a,b,c){a^3+b^2+c}",1,4,3)
Error in do.call(fc, list(...)) : couldn't find function
"function(a,b,c){a^3+b^2+c}"
This can be fixed by using eval and parse instead:
> doe=function(fc,...){eval(parse(text=fc))(...)}
> doe("sqrt",2)
[1] 1.414214
> doe("sum",1,2,3)
[1] 6
> doe("function(a,b,c){a^3+b^2+c}",1,4,3)
[1] 20
I see other solutions have been posted already. They're probably better.
Baz
______________________________________________
[email protected] mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html