[R] Scope and apply-type functions
jamie.f.olson
inspired2apathy at gmail.com
Thu Mar 17 19:01:41 CET 2011
So, I've been confused by this for a while. If I want to create functions in
an apply, it only uses the desired value for the variable if I create a new
local variable:
> lapply(1:5,function(h){k=h;function(){k}})[[1]]()
[1] 1
> lapply(1:5,function(k){function(){k}})[[1]]()
[1] 5
>
Normally, a function will use values for a variable if the variable is local
to the definition of the function:
> a = function(x){function(){x}}
> a(5)
function(){x}
> a(5)()
[1] 5
> a(6)()
[1] 6
So why doesn't this work for apply? Does apply work more like loops, with a
shared variable that changes values so that the first function defined
actually uses the last value of the variable?
> a = list();for (k in 1:5){a = c(a,function(){k})}
> a[[1]]()
[1] 5
>
Or is there something else entirely?
--
View this message in context: http://r.789695.n4.nabble.com/Scope-and-apply-type-functions-tp3385230p3385230.html
Sent from the R help mailing list archive at Nabble.com.
More information about the R-help
mailing list