[R] lapply not reading arguments from the correct environment

Gabor Grothendieck ggrothendieck at gmail.com
Fri May 18 19:42:06 CEST 2007


On 5/18/07, jiho <jo.irisson at gmail.com> wrote:
> On 2007-May-18  , at 18:21 , Gabor Grothendieck wrote:
> > In particular, we can use "[" directly instead of subset.  This is the
> > same as your function except for the line marked ### :
> >
> > myfun2 <- function() {
> >       foo = data.frame(1:10,10:1)
> >       foos = list(foo)
> >       fooCollumn=2
> >       cFoo = lapply(foos, "[", fooCollumn) ###
> >       return(cFoo)
> > }
> > myfun2() # test
> >
> > On 5/18/07, Prof Brian Ripley <ripley at stats.ox.ac.uk> wrote:
> >> 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.
>
> Thank you very much. Indeed it is much better this way. I got used to
> subset for data.frames because [ does not work with negative named
> arguments while select does. E.g.:
>        x[,-c("name1","name2")]
> does not work while
>        subset(x,select=-c("name1","name2"))
> works (it eliminates columns named name1 and name 2 from x). But I
> guess in most cases an other syntax can achieve the same thing with
> [, like:
>        x[,-which(names(x)%in%c("name1","name2"))]
> it's just a little less clear.

which is not needed.  Using builtin CO2:

      CO2[ ! names(CO2) %in% c("Type", "conc" ]

or

      CO2[ setdiff(names(CO2), c("Type", "conc")) ]



More information about the R-help mailing list