[R] unexpected scoping behavior with functions created in a loop

Antonio, Fabio Di Narzo antonio.fabio at gmail.com
Sun Dec 7 03:22:27 CET 2008


Hi guys.
I recently stumbled on an unexpected behavior of R when using
functions created in a loop.
The problem is silly enough to me that I had hard time choosing a good
mail subject, not talking about searching in the archives...
After some experiments, I trimmed down the following minimal
reproducible example:
#######
makeF <- function(i) function() i

fList <- list(makeF(1), makeF(2))
sapply(fList, do.call, list())
##This works as expected (by me...):
#[1] 1 2

##Things go differently when creating functions in a for loop:
for(i in 1:2)
  fList[[i]] <- makeF(i)
sapply(fList, do.call, list())
#[1] 2 2

##Same result with "lapply":
fList <- lapply(as.list(1:2), makeF)
sapply(fList, do.call, list())
#[1] 2 2
#######

I evidently overlook some important detail, but I still can't get it.
Somebody can explain me what's happening there?
Bests,
antonio.

> R.version
               _
platform       i686-pc-linux-gnu
arch           i686
os             linux-gnu
system         i686, linux-gnu
status         Patched
major          2
minor          8.0
year           2008
month          12
day            04
svn rev        47063
language       R
version.string R version 2.8.0 Patched (2008-12-04 r47063)
-- 
Antonio, Fabio Di Narzo
Ph.D. student at
Department of Statistical Sciences
University of Bologna, Italy



More information about the R-help mailing list