[R] using "aggregate" when variable names contain spaces
Dimitri Liakhovitski
dimitri.liakhovitski at gmail.com
Mon Apr 18 21:48:01 CEST 2011
That's great thanks a lot, David!
On Mon, Apr 18, 2011 at 3:47 PM, David Winsemius <dwinsemius at comcast.net> wrote:
>
> On Apr 18, 2011, at 3:40 PM, Dimitri Liakhovitski wrote:
>
>> That's helpful, thanks! Unfortunately, I cannot refer to all of my
>> variables to the left of tilda one by one - I have a lot of them.
>> Any way to get them in as a a bunch (somehow using mynames)?
>
> fmla <- as.formula(paste(
> paste("`", names(example)[2:3], "`", sep="", collapse="+"),
> "~group+mydate") )
>
> aggregate(fmla, sum,data=example)
>
>> Thanks!
>>
>> On Mon, Apr 18, 2011 at 3:34 PM, David Winsemius <dwinsemius at comcast.net>
>> wrote:
>>>
>>> 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
>>>
>>>
>>
>>
>>
>> --
>> Dimitri Liakhovitski
>> Ninah Consulting
>> www.ninah.com
>
> David Winsemius, MD
> West Hartford, CT
>
>
--
Dimitri Liakhovitski
Ninah Consulting
www.ninah.com
More information about the R-help
mailing list