[R] aggregating variables (sum within groups)

Jeff Newmiller jdnewmil at dcn.davis.CA.us
Thu Feb 26 16:18:43 CET 2015


For the record, the ave function in R can apply any function you specify, not just mean. The primary feature of ave is that it does not collapse the rows like aggregate does. Choose among them according to how you want the output to be organized.
---------------------------------------------------------------------------
Jeff Newmiller                        The     .....       .....  Go Live...
DCN:<jdnewmil at dcn.davis.ca.us>        Basics: ##.#.       ##.#.  Live Go...
                                      Live:   OO#.. Dead: OO#..  Playing
Research Engineer (Solar/Batteries            O.O#.       #.O#.  with
/Software/Embedded Controllers)               .OO#.       .OO#.  rocks...1k
--------------------------------------------------------------------------- 
Sent from my phone. Please excuse my brevity.

On February 26, 2015 4:02:49 AM PST, David Studer <studerov at gmail.com> wrote:
>Hello everybody!
>
>I have a (probabely very easy) problem. Even though I was looking in
>several r-books
>I could not find a suitable function to this problem, that's why I hope
>that someone here
>could help me:
>
># Sample data:
>group<-c("A","A","A","B","B","C","C","C")
>var1<-c(1,0,0,1,1,0,NA,1)
>var2<-c(0,1,NA,0,1,1,0,0)
>testdata<-data.frame(group, var1, var2)
>
>Now, I'd like to generate two aggregated variables:
>
>testdata$x<- ???   should count the sum of var1 within each group (=4)
>testdata$y<- ???   should count the sum of var2 within each group (=3)
>
>Therefore I am looking for a function like ave() which does not
>calculate
>the mean value but a sum.
>
>Thank you for any hints!
>
>David
>
>	[[alternative HTML version deleted]]
>
>______________________________________________
>R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
>https://stat.ethz.ch/mailman/listinfo/r-help
>PLEASE do read the posting guide
>http://www.R-project.org/posting-guide.html
>and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list