【问题标题】:Identify observations conditionally有条件地识别观察
【发布时间】:2021-02-11 00:53:55
【问题描述】:

我的数据集如下:

ID     Type
55523  Ref
55523  Ref
19999  Ref
19999  View
55523  Ref
33333  View
33333  View
33333  Ref
11111  Ref

我想要一个新的数据框来标识只有 Ref 类型的 ID,而没有其他的。我想保留重复项。结果如下:

ID     Type
55523  Ref
55523  Ref
55523  Ref
11111  Ref

提前谢谢你。

【问题讨论】:

    标签: r


    【解决方案1】:

    选择 ID,其中 allType 值为 'Ref'

    这可以在基础 R 中完成:

    subset(df, ave(Type == 'Ref', ID, FUN = all))
    
    #     ID Type
    #1 55523  Ref
    #2 55523  Ref
    #5 55523  Ref
    #9 11111  Ref
    

    dplyr

    library(dplyr)
    df %>% group_by(ID) %>% filter(all(Type == 'Ref'))
    

    data.table

    library(data.table)
    setDT(df)[, .SD[all(Type == 'Ref')], ID]
    

    【讨论】:

      【解决方案2】:
      library(dplyr)
      library(tibble)
      
      tb <- tribble(~ID, ~Type,
      55523,  "Ref",
      55523,  "Ref",
      19999,  "Ref",
      19999,  "View",
      55523,  "Ref",
      33333,  "View",
      33333,  "View",
      33333,  "Ref",
      11111,  "Ref")
      
      a <- tb %>% count(ID, Type) %>% group_by(ID) %>% count(ID) %>% filter(n == 1)
      
      b <- tb %>% semi_join(a, by = c("ID" = "ID"))
      b 
      # A tibble: 4 x 2
           ID Type 
        <dbl> <chr>
      1 55523 Ref  
      2 55523 Ref  
      3 55523 Ref  
      4 11111 Ref 
      

      【讨论】:

      • 对不起!我是stackoverflow的新手。我不知道这是怎么回事?我只是想投票
      • 抱歉!我不是故意的,我是stackoverflow的新手!我试图调整它,但它似乎没有投票..
      • @nyk 如果您进行编辑,那么 Kate 将能够更改投票
      • @Kate 没关系。反对票已被删除。感谢 akrun 的建议。
      【解决方案3】:
      df = data.frame(
          "ID" = c(55523, 55523, 19999, 19999, 55523, 33333, 33333, 33333, 11111),
          "Type" = c("Ref", "Ref", "Ref", "View", "Ref", "View", "View", "Ref", "Ref")
          )
      
      ref = df[df$Type == "Ref",]
      other = df[df$Type != "Ref",]
      
      ref[!ref$ID %in% other$ID,]
      #      ID Type
      # 1 55523  Ref
      # 2 55523  Ref
      # 5 55523  Ref
      # 9 11111  Ref
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多