这个问题在这里已经有了答案:
How to select the rows with maximum values in each group with dplyr? [duplicate]
(6 个回答)
去年关闭。
我有一个如下所示的数据集:
game teams score
Liverpool - Leeds Liverpool 2
Liverpool - Leeds Leeds 1
Sheffield - Norwich Sheffield 0
Sheffield - Norwich Norwich 1
Arsenal - Newcastle Arsenal 3
Arsenal - Newcastle Newcastle 2
我的目的是只保留与获胜团队相对应的行。我想要的输出看起来像这样:game teams score
Liverpool - Leeds Liverpool 2
Sheffield - Norwich Norwich 1
Arsenal - Newcastle Arsenal 3
我想我首先需要按游戏对行进行分组,但是一旦完成,我就无法成功前进。
最佳答案
一种可能 dplyr
解决方案是
df %>%
group_by(game) %>%
filter(score == max(score))
# A tibble: 6 x 3
# Groups: game [5]
# game teams score
# <chr> <chr> <int>
# 1 Liverpool - Leeds Liverpool 2
# 2 Sheffield - Norwich Norwich 1
# 3 Arsenal - Newcastle Arsenal 3
使用此解决方案,您将在平局的情况下获得两支球队。
关于r - Dplyr:按条件过滤成对分组数据集,每对只保留一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62919247/