R does this sort of thing easily without any parse/eval acrobatics needed.
E.g., you can do:
> stu <- function(x) {return( 1 + (2*x*x) - (3*x) )}
> (x <- 0:3)
[1] 0 1 2 3
> stu(x)
[1] 1 0 3 10
> metafun <- function(FUN, data) FUN(data)
> metafun(stu, x)
[1] 1 0 3 10
> # if you want to be able use a character-data name for the function:
> metafun2 <- function(FUN, data) {if (is.character(FUN)) FUN <-
getFunction(FUN); FUN(data)}
> metafun2("stu", x)
[1] 1 0 3 10
> metafun2(stu, x)
[1] 1 0 3 10
>
What went wrong with your code was that your parse() constructed a list of
4 expressions, and evaluating that returned the value of the last one:
> (fun <- "stu")
[1] "stu"
> paste( fun, "(", x, ")", sep = "" )
[1] "stu(0)" "stu(1)" "stu(2)" "stu(3)"
> parse( text = paste( fun, "(", x, ")", sep =
"" ) )
expression(stu(0), stu(1), stu(2), stu(3))
attr(,"srcfile")
<text>
>
(Others have observed that in a very large proportion of the situations
where people reach for parse/eval, there's a neater, cleaner & more
direct
way of doing the job.)
-- Tony Plate
Talbot Katz wrote:> Hi.
>
> I'm looking for an R equivalent to something like function pointers in
C/C++. I have a search procedure that evaluates the fitness of each point it
reaches as it moves along, and decides where to move next based on its fitness
evaluation. I want to be able to pass different fitness functions to this
procedure. I am trying to find a good way to do this. I was thinking of
passing in the name of the function and then using eval. However, I haven't
gotten this to work the way I'd like it to. Consider the following example:
>
>
>> stu <- function(x) {return( 1 + (2*x*x) - (3*x) )}> (x=0:3)[1] 0
1 2 3> stu(x)[1] 1 0 3 10> (fun="stu")[1] "stu">
eval( parse( text = paste( fun, "(", x, ")", sep =
"" ) ) )[1] 10>
>
>
> Notice that the function I defined called "stu" will operate on a
vector x and return a vector y = stu(x) such that y[i] equals stu(x[i]). When I
tried to pass stu and x to a procedure that would evaluate stu(x) I only get
stu(x[N]), when N is the last element of x. What am I doing wrong? Is there a
better way to pass function references?
>
> I can get the following to work, but it seems awfully clunky:
>
>> sapply( 1:length(x), function(i){ return( eval( parse( text = paste(
fun, "(", x[i], ")", sep = "" ) ) ) ) } )[1] 1 0
3 10>
>
> Thanks!
>
> -- TMK --212-460-5430 home917-656-5351 cell
> [[alternative HTML version deleted]]
>
> ______________________________________________
> 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.
>