r - Dplyr:按条件过滤成对分组数据集,每对只保留一行

标签 r dataframe filter dplyr

这个问题在这里已经有了答案:





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/

相关文章:

function - 评估 R 循环中的变量

python - 用另一个数据帧的值替换 Pandas 数据帧的多个值的最快方法

python - Pandas DataFrame 到字典列表

python - 数据帧单元格被锁定并用于运行余额计算,条件是同一行上另一个单元格的结果

flutter - 在 Android 移动应用中实现多个过滤器的简单方法

r - 在 data.table 中删除单个列的成语

r - parent.env(x)困惑

r - 安装自定义包时在 'lib.loc' 中未找到库树

Rosetta Stone 上的 C 快速中值滤波器(C I/O 和图像)

php - 如何过滤字符串中的多个限制词?