[R] functional (?) programming in r

Thomas Lumley tlumley at u.washington.edu
Tue Nov 18 04:44:16 CET 2008


On Mon, 17 Nov 2008, jim holtman wrote:

> You can use the 'local' function to make sure you create a value of
> 'i' that is defined when the function is defined:
>
>> funcs = lapply(1:5, function(i)local({i; function(){ i}}))

You can use pretty much any other function, too
  funcs = lapply(1:5, function(i) {cos(i); function() i})
or no function at all
  funcs = lapply(1:5, function(i) {i=i; function() i})

The only requirement is to make sure that i is evaluated.
The force() function was created for exactly this situation, to make it 
obvious that you are just forcing lazy evaluation.

  funcs = lapply(1:5, function(i) {force(i); function() i})

 	-thomas

Thomas Lumley			Assoc. Professor, Biostatistics
tlumley at u.washington.edu	University of Washington, Seattle



More information about the R-help mailing list