marc
marc

Reputation: 413

Filter all group if one element satisfy a condition in dplyr

I have the following data:

df1 <- data.frame( id = c(1,1,2) , a = c('a','b','c'))
> df1
  id a
1  1 a
2  1 b
3  2 c

I would like to filter (remove) all element of a group defined on a variable if at least one element of the group satisfy a given condition. Here, suppress lines corresponding to an id if variable a equals 'a'.

I tried the following, which removes only the line with a == 'a' as I wish the group with id == 1 would be filtered

> df1 %>%
+   group_by( id ) %>%
+   filter(  a != 'a')
# A tibble: 2 × 2
# Groups:   id [2]
     id a    
  <dbl> <chr>
1     1 b    
2     2 c    

Any help would be welcome

Upvotes: 1

Views: 1631

Answers (1)

akrun
akrun

Reputation: 887991

Perhaps use all

library(dplyr)
df1 %>% 
 group_by(id) %>% 
 filter(all(a != 'a')) %>%
 ungroup

Or with any

df1 %>%
  group_by(id) %>%
  filter(!any(a == 'a')) %>%
  ungroup

Or may use %in% as well

df1 %>%
  group_by(id) %>%
  filter(!'a' %in% a) %>%
  ungroup

Upvotes: 4

Related Questions