[R] Using apply to get group means

hadley wickham h.wickham at gmail.com
Tue Mar 31 18:38:40 CEST 2009


On Tue, Mar 31, 2009 at 11:31 AM, baptiste auguie <ba208 at exeter.ac.uk> wrote:
> Not exactly the output you asked for, but perhaps you can consider,
>
> library(doBy)
>> summaryBy(x3~x2+x1,data=x,FUN=mean)
>>
>>  x2 x1 x3.mean
>> 1  1  A     1.5
>> 2  1  B     2.0
>> 3  1  C     3.5
>> 4  2  A     4.0
>> 5  2  B     5.5
>> 6  2  C     6.0
>
>
> the plyr package also provides similar functionality, as do the ?by, ?ave,
> and ?tapply base functions.

In plyr it would look like:

x1 <- rep(c("A", "B", "C"), 3)
x2 <- c(rep(1, 3), rep(2, 3), 1, 2, 1)
x3 <- c(1, 2, 3, 4, 5, 6, 2, 6, 4)
df <- data.frame(x1, x2, x3)

ddply(df, .(x1, x2), transform, x3.mean = mean(x3))

Note how I created the data frame - only use cbind if you want a
matrix (i.e. all the columns have the same type)

Hadley


-- 
http://had.co.nz/




More information about the R-help mailing list