【问题标题】:How to delete rows with speicifc column condition in r? [duplicate]如何删除r中具有特定列条件的行? [复制]
【发布时间】:2020-09-10 08:00:50
【问题描述】:

你好,我的 df 看起来像

PID Stage
123  1
123  2
123  4
124  1
124  3
137  2
137  3
153  1
153  4
153  5
167  4
167  5
178  1
178  2
178  1
187  3
187  4 

我想根据 >= 4 Stage 的行删除记录

预期输出

PID Stage
124  1
124  3
137  2
137  3
178  1
178  2
178  1

提前致谢

【问题讨论】:

  • RowsOfInterest <- df[ , 'Stage' ] < 4; Result <- df[ RowsOfInterest , ];

标签: r dplyr tidyverse tidyr


【解决方案1】:

选择all 的值小于 4 的组。

library(dplyr)
df %>% group_by(PID) %>%filter(all(Stage < 4))

#    PID Stage
#  <int> <int>
#1   124     1
#2   124     3
#3   137     2
#4   137     3
#5   178     1
#6   178     2
#7   178     1

这个可以写成data.table

library(data.table)
setDT(df)[, .SD[all(Stage < 4)], PID]

和基础R:

subset(df, ave(Stage < 4, PID, FUN = all))

数据

df <- structure(list(PID = c(123L, 123L, 123L, 124L, 124L, 137L, 137L, 
153L, 153L, 153L, 167L, 167L, 178L, 178L, 178L, 187L, 187L), 
    Stage = c(1L, 2L, 4L, 1L, 3L, 2L, 3L, 1L, 4L, 5L, 4L, 5L, 
    1L, 2L, 1L, 3L, 4L)), class = "data.frame", row.names = c(NA, -17L))

【讨论】:

    【解决方案2】:

    没有group_by()dplyr 解决方案:

    library(dplyr)
    
    df %>% filter(!PID %in% PID[Stage >= 4])
    
    #   PID Stage
    # 1 124     1
    # 2 124     3
    # 3 137     2
    # 4 137     3
    # 5 178     1
    # 6 178     2
    # 7 178     1
    

    base 版本:

    subset(df, !PID %in% PID[Stage >= 4])
    

    【讨论】:

      猜你喜欢
      • 2021-04-01
      • 2021-08-17
      • 2018-08-06
      • 2019-06-05
      • 2022-01-23
      • 2022-01-22
      • 1970-01-01
      • 2019-07-30
      • 1970-01-01
      相关资源
      最近更新 更多