r - 按ID分组并仅过滤平均值最大的组

标签 r dataframe dplyr

我有一个 DF,如下所示,

a <- data.frame(group =c(1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5), count = c(12L, 80L, 102L, 97L, 118L, 115L, 4L, 13L, 136L,114L, 134L, 126L, 128L, 63L, 118L, 1L, 28L, 18L, 18L, 23L))

   group count
1      1    12
2      1    80
3      1   102
4      1    97
5      2   118
6      2   115
7      2     4
8      2    13
9      3   136
10     3   114
11     3   134
12     3   126
13     4   128
14     4    63
15     4   118
16     4     1
17     5    28
18     5    18
19     5    18
20     5    23

我使用了以下命令,
a %>% group_by(group) %>% summarise(mean(count))

  group mean(count)
  (dbl)       (dbl)
1     1       72.75
2     2       62.50
3     3      127.50
4     4       77.50
5     5       21.75

我想过滤掉属于最高均值的组条目。在这里说第三组包含最大平均值,所以我的输出应该是,
   group count
1     3   136
2     3   114
3     3   134
4     3   126

任何人都可以给一些想法如何做到这一点?

最佳答案

如果您想查看基本的 R 解决方案,可以使用 which.maxaggregate 执行此操作:

# calculate means by group
myMeans <- aggregate(count~group, a, FUN=mean)

# select the group with the max mean
maxMeanGroup <- a[a$group == myMeans[which.max(myMeans$count),]$group, ]

作为第二种方法,您可以尝试 data.table :
library(data.table)
setDT(a)

a[group == a[, list("count"=mean(count)), by=group
             ][, which.max(count)], ]

返回
   group count
1:     3   136
2:     3   114
3:     3   134
4:     3   126

关于r - 按ID分组并仅过滤平均值最大的组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37710684/

相关文章:

r - 具有重复列名的堆栈

r - CRAN 可接受的链接到 OpenMP 的方式,某些从 Rcpp 调用的 C 代码

r - R 中数据帧列表的交叉

python - Pandas - 合并和比较两个 DataFrame(一个独特的列)

r - 使用 dplyr 在组之间插入虚拟多个 X 行?

r - 使用源行号分析已安装的 R 包?

python - 在Python中合并两个不规则数据框

python - 为 Pandas 数据框中满足条件的列打印特定列(代码有效,只需帮助将其减少为一行代码)

r - 无法删除列 - select() with dplyr

r - 根据列中的唯一值查找两个最大日期之间的最小日期