【问题标题】:How to delete entire ids with event in R [duplicate]如何在R中删除带有事件的整个ID [重复]
【发布时间】:2020-10-14 06:13:12
【问题描述】:

我有一个df 看起来像

ID  Drugs       Event
123 Insulin     1
123 Bigunaides  2
123 SGLT2       3
234 Insulin     1
234 SGLT2       3
345 Bigunaides  2
345 SGLT2       3
456 SGLT2       3
567 DPP4        4

如果有 Event == 1,我想删除整个 id

预期输出

ID  Drugs      Event
345 Bigunaides  2
345 SGLT2       3
456 SGLT2       3
567 DPP4        4

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    我们可以通过filter 进行分组。按“ID”分组,filter“事件”没有 1 的所有组

    library(dplyr)
    df1 %>%
         group_by(ID) %>%
         filter( all(Event != 1))
    

    -输出

    # A tibble: 4 x 3
    # Groups:   ID [3]
    #     ID Drugs      Event
    #  <int> <chr>      <int>
    #1   345 Bigunaides     2
    #2   345 SGLT2          3
    #3   456 SGLT2          3
    #4   567 DPP4           4
    

    或者另一种选择是

    df1 %>%
        group_by(ID) %>%
        filter(!1 %in% Event)
    

    -输出

    # A tibble: 4 x 3
    # Groups:   ID [3]
    #     ID Drugs      Event
    #  <int> <chr>      <int>
    #1   345 Bigunaides     2
    #2   345 SGLT2          3
    #3   456 SGLT2          3
    #4   567 DPP4           4
    

    注意:两种解决方案都有效

    数据

    df1 <- structure(list(ID = c(123L, 123L, 123L, 234L, 234L, 345L, 345L, 
    456L, 567L), Drugs = c("Insulin", "Bigunaides", "SGLT2", "Insulin", 
    "SGLT2", "Bigunaides", "SGLT2", "SGLT2", "DPP4"), Event = c(1L, 
    2L, 3L, 1L, 3L, 2L, 3L, 3L, 4L)), class = "data.frame", row.names = c(NA, 
    -9L))
    

    【讨论】:

      猜你喜欢
      • 2022-01-02
      • 2013-11-25
      • 2017-06-12
      • 2021-07-10
      • 1970-01-01
      • 1970-01-01
      • 2021-05-22
      • 2022-01-23
      • 1970-01-01
      相关资源
      最近更新 更多