[R] "aggregate" in R

Ista Zahn izahn at psych.rochester.edu
Tue Feb 22 23:44:34 CET 2011


Hi Gary,
I'm not sure if you can do that with aggregate. You might have to
resort to something like

tmp <- cbind(aggregate(y$a, by=list(y$x),  mean), aggregate(y$b,
by=list(y$x),  sum)$x)
names(tmp) <- c("x", "mean.a", "sum.b")
tmp

Or, using the plyr package:

library(plyr)
ddply(y, .(x), summarize, mean.a=mean(a), sum.b=sum(b))

Best,
Ista

On Tue, Feb 22, 2011 at 5:25 PM, Hongwei Dong <pdxdong at gmail.com> wrote:
> Hi, R users,
>
> I'm wondering how I can aggregate data in R with different functions for
> different columns. For example:
>
> x<-rep(1:5,3)
> y<-cbind(x,a=1:15,b=21:35)
> y<-data.frame(y)
>
> I want to aggregate "a" and "b" in y by "x". With "a", I want to use
> function "mean"; with "b", I want to use function "sum". I tried:
>
>> aggregate(y,x,mean(y$a),sum(y$b))
>
> But I got the error:
>
> Error in match.fun(FUN) :
>  'mean(y$a)' is not a function, character or symbol
>
>
> Anyone can tell me how to fix this problem? Thanks.
>
> Gary
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> 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.
>



-- 
Ista Zahn
Graduate student
University of Rochester
Department of Clinical and Social Psychology
http://yourpsyche.org



More information about the R-help mailing list