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

Dimitri Liakhovitski dimitri.liakhovitski at gmail.com
Thu Jul 14 21:05:55 CEST 2011


Hello!

I am aggregating using a formula in aggregate - of the type:
aggregate(cbind(var1,var2,var3)~factor1+factor2,sum,data=mydata)

However, I actually have an object (vector of my variables to be aggregated):
myvars<-c("var1","var2","var3")

I'd like my aggregate formula (its "cbind" part) to be able to use my
"myvars" object. Is it possible?
Thanks for your help!

Dimitri

Reproducible example:

mydate = rep(seq(as.Date("2008-12-01"), length = 3, by = "month"),4)
value1=c(1,10,100,2,20,200,3,30,300,4,40,400)
value2=c(1.1,10.1,100.1,2.1,20.1,200.1,3.1,30.1,300.1,4.1,40.1,400.1)

example<-data.frame(mydate=mydate,value1=value1,value2=value2)
example$group<-c(rep("group1",3),rep("group2",3),rep("group1",3),rep("group2",3))
example$group<-as.factor(example$group)
(example);str(example)

example.agg1<-aggregate(cbind(value1,value2)~group+mydate,sum,data=example)
# this works
(example.agg1)

### Building my object (vector of 2 names - in reality, many more):
myvars<-c("value1","value2")
example.agg1<-aggregate(cbind(myvars)~group+mydate,sum,data=example)
### does not work


-- 
Dimitri Liakhovitski
Ninah Consulting
www.ninah.com



More information about the R-help mailing list