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

Gabor Grothendieck ggrothendieck at gmail.com
Sun Dec 7 04:13:13 CET 2008


The missing item is lazy evaluation.  Try forcing the evaluation of i
and then repeat:

makeF <- function(i) { force(i); function() i }


On Sat, Dec 6, 2008 at 9:22 PM, Antonio, Fabio Di Narzo
<antonio.fabio at gmail.com> wrote:
> 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
>
> ______________________________________________
> R-help at 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.
>



More information about the R-help mailing list