[R] lapply not reading arguments from the correct environment

Prof Brian Ripley ripley at stats.ox.ac.uk
Fri May 18 18:05:40 CEST 2007


You need to study carefully what the semantics of 'subset' are.  The 
function body of myfun is not in the evaluation environment.  (The issue 
is 'subset', not 'lapply': select is an *expression* and not a value.)

Hint: using subset() programmatically is almost always a mistake.  R's 
subsetting function is '[': subset is a convenience wrapper.

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 am building a list of dataframes, in each of which I want to keep
> only column 2 (obviously I would not do it this way in real life but
> that's just to demonstrate the bug).
> If I execute the commands inline it works but if I clean my
> environment, then define the function and then execute:
> 	> myfun()
> I get this error:
> 	Error in eval(expr, envir, enclos) : object "fooCollumn" not found
> while fooCollumn is defined, in the function, right before lapply. In
> addition, if I define it outside the function and then execute the
> function:
> 	> fooCollumn=1
> 	> myfun()
> it works but uses the value defined in the general environment and
> not the one defined in the function.
> 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?

It is a bug, in your function.

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595



More information about the R-help mailing list