[R] using "aggregate" when variable names contain spaces

David Winsemius dwinsemius at comcast.net
Mon Apr 18 21:34:35 CEST 2011


On Apr 18, 2011, at 3:19 PM, Dimitri Liakhovitski wrote:

> Hello!
>
> my data set has many variables. Unfortuantely, many of those variables
> contain spaces in their names.
> I need advice on: how to refer to variable names in the formula for
> "aggregate". See example below:
>
> ### Generating example data set:
> 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))
> exampe$group<-as.factor(exampe$group)
>
> ### Generating variable names with spaces:
> names(example)<-c("mydate", "my value 1","my value 2","group")
>
> ### Trying to aggregate - but it's not working. Clearly, my reference
> to variable names is incorrect:
> mynames<-names(example)
> example.agg1<-aggregate(cbind(mynames)~group+mydate,sum,data=example)

Use backticks:

 > aggregate(`my value 1` + `my value 2` ~group+mydate,sum,data=example)
    group     mydate `my value 1` + `my value 2`
1 group1 2008-12-01                         8.2
2 group2 2008-12-01                        12.2
3 group1 2009-01-01                        80.2
4 group2 2009-01-01                       120.2
5 group1 2009-02-01                       800.2
6 group2 2009-02-01                      1200.2
>


-- 

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list