[Rd] iterated lapply

Radford Neal radford at cs.toronto.edu
Tue Feb 24 12:39:08 CET 2015

From: Daniel Kaschek <daniel.kaschek at physik.uni-freiburg.de>
> ... When I evaluate this list of functions by
> another lapply/sapply, I get an unexpected result: all values coincide.
> However, when I uncomment the print(), it works as expected. Is this a
> bug or a feature?
> conditions <- 1:4
> test <- lapply(conditions, function(mycondition){
>   #print(mycondition)
>   myfn <- function(i) mycondition*i
>   return(myfn)
> })
> sapply(test, function(myfn) myfn(2))

From: Jeroen Ooms <jeroenooms at gmail.com>
> I think it is a bug. If we use substitute to inspect the promise, it
> appears the index number is always equal to its last value:

From: Duncan Temple Lang <dtemplelang at ucdavis.edu>
> Not a bug, but does surprise people. It is lazy evaluation.

I think it is indeed a bug.  The lapply code saves a bit of time by
reusing the same storage for the scalar index number every iteration.
This amounts to modifying the R code that was used for the previous
function call.  There's no justification for doing this in the
documentation for lapply.  It is certainly not desired behaviour,
except in so far as it allows a slight savings in time (which is
minor, given the time that the function call itself will take).

   Radford Neal

More information about the R-devel mailing list