Select groups which have at least one of a certain value

This turns out to be pretty easy: you just need to use the any() function in the filter call. Indeed, it appears that:

  • filter(any(...)) evaluates at the group_by() level,

  • filter(...) evaluates at the rowwise() level, even when preceded by group_by().

Hence use:

 df %>%
    group_by(Group) %>%
    filter(any(Value==4)) 

Group Value
 <fctr> <int>
1      B     3
2      B     4

Interestingly, the same appear with mutate, compare:

df %>%
group_by(Group) %>%
mutate(check1=any(Value==4), 
       check2=Value==4) 

   Group Value check1 check2
  <fctr> <int>  <lgl>  <lgl>
1      A     1  FALSE  FALSE
2      A     2  FALSE  FALSE
3      B     3   TRUE  FALSE
4      B     4   TRUE   TRUE

Leave a Comment