[R] Assignments inside lapply

Thomas Lumley tlumley at uw.edu
Wed Apr 27 22:50:27 CEST 2011

On Wed, Apr 27, 2011 at 10:12 PM, Kenn Konstabel <lebatsnok at gmail.com> wrote:
> On Wed, Apr 27, 2011 at 12:58 PM, Nick Sabbe <nick.sabbe at ugent.be> wrote:
>> No, that does not work.
>> You cannot do assignment within (l)apply.
>> Nor in any other function for that matter.
> Yes that may work if you want to.
> You can do non-local assignment within lapply using <<- (and, for that
> matter, within any other function) but there is no one-word answer to
> the question whether this is a good idea.

"No" is a fairly good one-word answer in the case of lapply().

The main virtue of the *apply family is the simpler mental model
resulting from thinking functionally, and you really don't want to
mess that up by using functions with side effects.   Especially as the
order of evaluation in lapply(), and thus the order of the
side-effects, isn't specified. Who knows, someday it might run in


Thomas Lumley
Professor of Biostatistics
University of Auckland

More information about the R-help mailing list