This has been asked before, but I just cannot figure out why lapply should behave this way given that R uses lazy evalution. Even after reading (or at least trying to read) parts of the R language definition.
> f <- function(x) {function() {x}} > a <- list(f(1), f(2), f(3)) > a[[1]]() # as expected [1] 1 > a[[2]]() # as expected [1] 2 > a[[3]]() # as expected [1] 3 > b <- sapply(1:3, f) > b[[1]]() # why? [1] 3 > b[[2]]() # why? [1] 3 > b[[3]]() # expected, kind of... [1] 3 Now I know that if I force the evaluation of x inside my function f, that the behaviour will change, i.e., b[[1]]() will return the value 1 etc. But could some knowledgeable person please tell me how the lazy evaluation as implemented in R results in, what I preceive to be, a very strange behaviour when using lapply as above? I thought that lapply calls f three times and returns a list with whatever f returned. Is this not so? /ali ______________________________________________ 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.