From radford at cs.toronto.edu  Tue Feb 24 12:39:08 2015
From: radford at cs.toronto.edu (Radford Neal)
Date: Tue, 24 Feb 2015 06:39:08 -0500
Subject: [Rd] iterated lapply
In-Reply-To: <mailman.21.1424775604.19275.r-devel@r-project.org>
References: <mailman.21.1424775604.19275.r-devel@r-project.org>
Message-ID: <20150224113908.GA7612@cs.toronto.edu>

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



[Rd] iterated lapply
Radford Neal