Reputation: 1359
I have a data-frame "dat" that this similar to the following:
team a b c
1 5 6 2
1 2 8 1
1 5 10 30
2 1 3 55
2 4 4 4
2 6 11 66
3 10 1 .5
3 3 4 24
3 4 44 60
I am trying to turn this into a data-frame so that the mean of each variable (a,b, and c) is calculated for each team. So that the final result looks like:
team a b c
1 4 8 11
2 3.7 6 41.7
3 5.7 16.3 28.2
They don't all have to be to 1 decimal, but the point is the same. Thank you!
Upvotes: 0
Views: 78
Reputation: 887611
We can some either dplyr/data.table
or base R
aggregate
to do this.
Using dplyr
, we group by 'team' and then with summarise_each
, we get the mean
library(dplyr)
dat %>%
group_by(team) %>%
summarise_each(funs(mean))
Or in data.table
, we convert the 'data.frame' to 'data.table' (setDT(dat)
), grouped by 'team', we loop with lapply
to get the 'mean' of the other columns.
library(data.table)
setDT(dat)[, lapply(.SD, mean), team]
Or we can use the formula method of aggregate
from base R
to get the mean
. We have to specify .
at the LHS of the formula to signify all other columns.
aggregate(.~team, dat, mean)
Upvotes: 2