Re: [R] lapply not reading arguments from the correct environment

From: Thomas Lumley <>
Date: Fri, 18 May 2007 08:09:08 -0700 (PDT)

On Fri, 18 May 2007, jiho wrote:

> Hello,
> I am facing a problem with lapply which I ''''think''' may be a bug.
> This is the most basic function in which I can reproduce it:
> myfun <- function()
> {
> foo = data.frame(1:10,10:1)
> foos = list(foo)
> fooCollumn=2
> cFoo = lapply(foos,subset,select=fooCollumn)
> return(cFoo)
> }
> I get this error:
> Error in eval(expr, envir, enclos) : object "fooCollumn" not found
> while fooCollumn is defined, in the function, right before lapply.
> This is with R 2.5.0 on both OS X and Linux (Fedora Core 6)
> What did I do wrong? Is this indeed a bug? An intended behavior?

No, it isn't a bug (though it may be confusing).

The problem is that subset() evaluates its "select" argument in an unusual way. Usually the argument would be evaluated inside myfun() and the value passed to lapply(), and everything would work as you expect.

subset() bypasses the normal evaluation and explicitly evaluates the "select" argument in the calling frame, ie, inside lapply(), where fooCollumn is not visible.

You could do

   lapply(foos, function(foo) subset(foo, select=fooCollum)) capturing fooCollum by lexical scope. In R this is often a better option than passing extra arguments to lapply (or other functions that take function arguments).

         -thomas mailing list PLEASE do read the posting guide and provide commented, minimal, self-contained, reproducible code. Received on Fri 18 May 2007 - 15:50:31 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Fri 18 May 2007 - 16:30:57 GMT.

Mailing list information is available at Please read the posting guide before posting to the list.