[R] returning functions inside lapply

Ali Tofigh alix.tofigh at gmail.com
Tue Apr 24 22:22:57 CEST 2012


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



More information about the R-help mailing list