[R] lapply not reading arguments from the correct environment

jiho jo.irisson at gmail.com
Fri May 18 17:34:46 CEST 2007


On 2007-May-18  , at 17:09 , Thomas Lumley wrote:
> On Fri, 18 May 2007, jiho wrote:
>> 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?
>
> 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).

Thank you very much, this works well indeed. I agree it is a bit  
confusing, to say the least. The point is that supplying other  
arguments in the ... of lapply worked for all other functions I tried  
before (mean, sd, summary and even spline) so it is really a problem  
with subset. Anyway, R is great even with such little flaws here and  
there and as long as the community is there to support it, it will rule.

Cheers,

JiHO
---
http://jo.irisson.free.fr/



More information about the R-help mailing list