[R] Function reference

From: Talbot Katz <topkatz_at_msn.com>
Date: Wed, 19 Dec 2007 15:35:32 -0500

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!  


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. Received on Wed 19 Dec 2007 - 20:40:01 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Wed 19 Dec 2007 - 22:30:19 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.