Reputation: 1598
THIS POST seems relevant, but the example considers only one grouping variable (by
). Is it possible to use ave()
for several variables to be averaged on the basis of several grouping variables?
Following the example in the same POST:
df <- data.frame(A = rnorm(20), B = rnorm(20), site = gl(5,4), month = gl(2,10))
this seems to work fine, still using mean
not ave
aggregate(cbind(A, B) ~ site + month, data = df, mean)
Is there a more efficient way? Can ave()
do that straight away?
Upvotes: 2
Views: 72
Reputation: 73572
You can add more grouping variables.
> transform(df, mn=ave(cbind(A, B), site, month))
A B site month mn.A mn.B
1 -0.6104697 0.2524263 1 1 -0.03415871 -0.03415871
2 0.2880355 0.1897356 1 1 -0.03415871 -0.03415871
3 -0.5816155 1.2815789 1 1 -0.03415871 -0.03415871
4 1.3435948 -2.4365555 1 1 -0.03415871 -0.03415871
5 0.1750469 -0.5855076 2 1 -0.10553138 -0.10553138
6 0.4374662 0.0103783 2 1 -0.10553138 -0.10553138
7 -0.3405101 -0.8371708 2 1 -0.10553138 -0.10553138
8 0.6288837 -0.3328376 2 1 -0.10553138 -0.10553138
9 -1.6613419 -2.1050023 3 1 -0.72058797 -0.72058797
10 1.0453300 -0.1613377 3 1 -0.72058797 -0.72058797
11 0.5053064 -1.2946748 3 2 -0.13016572 -0.13016572
12 -1.9228812 2.1915868 3 2 -0.13016572 -0.13016572
13 -1.4860137 -0.3145034 4 2 -0.66294349 -0.66294349
14 -0.8653919 -0.3814499 4 2 -0.66294349 -0.66294349
15 0.1556521 -1.1469195 4 2 -0.66294349 -0.66294349
16 -0.9116240 -0.3532977 4 2 -0.66294349 -0.66294349
17 1.1310613 2.0196141 5 2 0.63761020 0.63761020
18 -0.6198639 0.8882268 5 2 0.63761020 0.63761020
19 0.3932094 -1.3104097 5 2 0.63761020 0.63761020
20 1.6947693 0.9042743 5 2 0.63761020 0.63761020
Note, that this is actually ave(cbind(A, B), site, month, FUN=mean)
, i.e. defaulting to mean
.
Upvotes: 2