[R] cbind in aggregate formula - based on an existing object (vector)

peter dalgaard pdalgd at gmail.com
Fri Jul 15 15:23:09 CEST 2011


On Jul 15, 2011, at 15:06 , peter dalgaard wrote:

> For a little lateral thinking, consider the use of "." on the LHS. That could play out as follows:
> 
>> myvars <- c("Ozone","Wind")
>> f <- . ~ Month
>> j <- union(all.vars(f[[3]]), myvars)
>> aggregate(. ~ Month, data=airquality[j], mean, na.rm=T)
>  Month    Ozone      Wind
> 1     5 23.61538 11.457692
> 2     6 29.44444 12.177778
> 3     7 59.11538  8.523077
> 4     8 59.96154  8.565385
> 5     9 31.44828 10.075862
> 
> (and of course, when you play with something unusual, a buglet pops up: it doesn't work with f instead of the explicit formula in the call to aggregate.)
> 


...however, once you go down that road, you might as well construct the LHS directly:

> lhs <- as.call(lapply(c("cbind", myvars), as.name))
> eval(bquote(aggregate(.(lhs) ~ Month, data=airquality, mean, na.rm=T)))
  Month    Ozone      Wind
1     5 23.61538 11.457692
2     6 29.44444 12.177778
3     7 59.11538  8.523077
4     8 59.96154  8.565385
5     9 31.44828 10.075862


-- 
Peter Dalgaard
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Email: pd.mes at cbs.dk  Priv: PDalgd at gmail.com



More information about the R-help mailing list