【问题标题】:filter for rows that meet multiple conditions in a column [duplicate]过滤满足列中多个条件的行[重复]
【发布时间】:2020-01-31 04:53:48
【问题描述】:

我正在尝试对 ID 与同一列中的两个值相关联的行进行子集化或过滤(每个“ID”和关联条件“DIR”都有一行)

我无法在 dplyr 过滤器或子集函数中解决这个问题

x <- data.frame("ID"=c(1,2,2,3,3,3,4,4,4,4),
              "DIR"=c("up","up","down","up","up","up","down","down","down","down"))

我已经尝试过两种变化:

subset(x, DIR=="up" & DIR=="down") 

x %>% group_by(ID) %>% filter(DIR=="up" & DIR=="down")

鉴于 ID #2 是唯一一个在 DIR 列中同时具有“向上”和“向下”的 ID,我想要的只是剩下的两行

它没有返回任何结果

【问题讨论】:

    标签: r filter dplyr conditional-statements subset


    【解决方案1】:

    在按“ID”分组后,filter 通过检查 all 的元素 vector (c("up", "down")) 是 %in% 列“DIR”

    library(dplyr)
    x %>%
       group_by(ID) %>%
       filter(all(c("up", "down") %in% DIR) )
    # A tibble: 2 x 2
    # Groups:   ID [1]
    #     ID DIR  
    #  <dbl> <fct>
    #1     2 up   
    #2     2 down 
    

    或使用base R

    i1 <- with(x, as.logical(ave(as.character(DIR), ID, FUN = 
              function(x) all(c("up", "down") %in% x))))
    x[i1, ]
    #   ID  DIR
    #2  2   up
    #3  2 down
    

    【讨论】:

    • 这很好用!感谢您抽出宝贵时间提供帮助!
    猜你喜欢
    • 1970-01-01
    • 2022-12-21
    • 2021-11-30
    • 2018-02-19
    • 1970-01-01
    • 2017-10-13
    • 2020-01-30
    • 1970-01-01
    • 2019-10-16
    相关资源
    最近更新 更多