[R] outputting functions in lapply
Duncan Murdoch
murdoch at stats.uwo.ca
Mon Dec 7 15:26:39 CET 2009
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
More information about the R-help
mailing list