Skip to content
Prev 175637 / 398503 Next

Using apply to get group means

That is precisely the reason for the existence of the ave function.  
Using Wickham's example:

 > 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)
 > df$grpx3 <- ave(df$x3, list(x1,x2))
 > df
   x1 x2 x3 grpx3
1  A  1  1   1.5
2  B  1  2   2.0
3  C  1  3   3.5
4  A  2  4   4.0
5  B  2  5   5.5
6  C  2  6   6.0
7  A  1  2   1.5
8  B  2  6   5.5
9  C  1  4   3.5

Note that the default function is mean() but other functions could be  
specified.