[R] problem with lapply(x, subset, ...) and variable select argument

Thomas Lumley tlumley at u.washington.edu
Tue Oct 11 16:31:00 CEST 2005


On Tue, 11 Oct 2005, joerg van den hoff wrote:
> many thanks to thomas and gabor for their help. both solutions solve my 
> problem perfectly.
>
> but just as an attempt to improve my understanding of the inner workings of R 
> (similar problems are sure to come up ...) two more question:
>
> 1.
> why does the call of the "[" function (thomas' solution) behave different 
> from "subset" in that the look up of the variable "n" works without providing 
> lapply with the current environment (which is nice)?

"[" behaves like nearly all functions in R: the value of the argument is 
passed.   subset() does some tricky things to subvert the usual argument 
passing.  Quite a few of the modelling functions do similar tricky things, 
and they do sometimes get confused when passed as arguments to another 
function.

> 2.
> using 'subset' in this context becomes more cumbersome, if sapply is used. it 
> seems that than I need
> ...
> environment(sapply) <- environment(lapply) <- environment()
> sapply(x, subset, select = n))
> ...
> to get it working (and that means you must know, that sapply uses lapply). or 
> can I somehow avoid the additional explicit definition of the 
> lapply-environment?

You really don't want to go around playing with environment() on 
functions. That way lies madness.  Use subset at the command line and [ or 
[[ in programming.  I don't think I have ever set environment() on a 
function (only on formulas).


 	-thomas




More information about the R-help mailing list