根据团队在r中聚合数据帧 [英] aggregate data-frame by team in r

查看:149
本文介绍了根据团队在r中聚合数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框dat,类似于以下内容:

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

我正在尝试将其转换为数据框,以便为每个团队计算每个变量(a,b和c)的平均值。所以最终结果如下所示:

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

他们并不都必须是1小数,点是一样的。谢谢!

They don't all have to be to 1 decimal, but the point is the same. Thank you!

推荐答案

我们可以使用 dplyr / data.table base R 聚合来执行此操作。

We can some either dplyr/data.table or base R aggregate to do this.

使用 dplyr ,我们按团队分组,然后使用 summarise_each ,我们得到 / code>

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))






或者在 data.table 中,我们将'data.frame'转换为'data.table'( setDT(dat) ),按团队分组,我们循环使用 lapply 获取其他列的平均值。


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]






或者我们可以使用 code>从 base R 获取意味着。我们必须在公式的LHS上指定来表示所有其他列。


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)

这篇关于根据团队在r中聚合数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆