aggregate data-frame by team in r

China☆狼群 提交于 2019-12-25 04:14:00

问题


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!


回答1:


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)


来源:https://stackoverflow.com/questions/32292696/aggregate-data-frame-by-team-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!