Filter groups in dplyr that exclusively contain specific combinations of values

后端 未结 2 911
面向向阳花
面向向阳花 2020-12-10 05:57

Given a table like:

  id value
1  1     a
2  2     a
3  2     b
4  2     c
5  3     c

I would like to filter for:

a) the ids that o

相关标签:
2条回答
  • 2020-12-10 06:33

    Try

    a)

    df %>% group_by(id) %>% filter(all(value == "a"))
    

    b)

    df %>% group_by(id) %>% filter(all(c("a", "b") %in% value))
    
    0 讨论(0)
  • 2020-12-10 06:33

    Here is an alternative approach that can be used both for a) and b)

    df %>% group_by(id) %>% arrange(value) %>% summarize(value=paste(value,collapse="")) %>% filter(grepl("ab",value))
    

    Result:

         id value
      (dbl) (chr)
    1     2   abc
    

    Hope this helps

    0 讨论(0)
提交回复
热议问题