[R] unexpected behavior when creating a list of functions

From: Matthew Suderman <matthewsuderman_at_yahoo.com>
Date: Wed 04 Apr 2007 - 22:10:54 GMT


I wanted to create a list of functions whose output differs depending the value of a variable when the function was created. Generally this did not work. Each function was exactly the same, as in the simple example below:

get_data_function <- function(v) {
  function() {
    print(v)
  }
}
data_functions <- sapply(1:10,function(v) get_data_function(v)) (data_functions[[1]])() # prints 10!

However, if I insert a statement in get_data_function to print argument v, then I get the different functions that I wanted:

get_data_function <- function(v) {
  print(v)
   function() {
     print(v)
   }
 }
 data_functions <- sapply(1:10,function(v) get_data_function(v))  (data_functions[[1]])() # prints 1, as expected!  

I have two questions about this:
* Is this a bug in R?

Matt  



Don't get soaked. Take a quick peek at the forecast

        [[alternative HTML version deleted]]



R-help@stat.math.ethz.ch 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 Thu Apr 05 08:17:37 2007

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Wed 04 Apr 2007 - 23:31:23 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.