On 07/12/2009 8:53 AM, Rune Schjellerup Philosof wrote:
How come the k is 3 in all of this output?
I expected it to be equal to r.
> tmp3 <- lapply(1:3, function(k) function(r) print(paste(r, "<- r | k
->", k)))
> for (i in 1:3) { tmp3[[i]](i) }
[1] "1 <- r | k -> 3"
[1] "2 <- r | k -> 3"
[1] "3 <- r | k -> 3"
Because of lazy evaluation. The argument k never gets evaluated in the
lapply loop. Add "force(k)" before you create the function, and you'll
get the expected output:
> tmp3 <- lapply(1:3, function(k) { force(k); function(r)
print(paste(r, "<- r | k ->", k))} )
> for (i in 1:3) { tmp3[[i]](i) }
[1] "1 <- r | k -> 1"
[1] "2 <- r | k -> 2"
[1] "3 <- r | k -> 3"
Duncan Murdoch
______________________________________________
R-help@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.