[R] lapply not reading arguments from the correct environment

Thomas Lumley tlumley at u.washington.edu
Fri May 18 17:09:08 CEST 2007


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)
> }
>
<snip>
> I get this error:
> 	Error in eval(expr, envir, enclos) : object "fooCollumn" not found
> while fooCollumn is defined, in the function, right before lapply.
<snip>
> 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



More information about the R-help mailing list