Filter for column value if another column contains a value

Viewed 301

Essentially I would like to filter a column if another column contains a value. Here is an example:

my_df <- data.frame(x = c(1,1,1,2,2,2),
           y = c(1,2,3,4,5,6)) 
> my_df
  x y
1 1 1
2 1 2
3 1 3
4 2 4
5 2 5
6 2 6

Let's filter x!=1 if and only if y!=1. Here is my expected result:

  x y
1 1 1
2 2 4
3 2 5
4 2 6
1 Answers

We can use a group_by filter here

library(dplyr)
my_df %>%
   group_by(x) %>% 
   filter(if(any(y == 1)) y == 1 else TRUE)
# A tibble: 4 x 2
# Groups:   x [2]
#      x     y
#  <dbl> <dbl>
#1     1     1
#2     2     4
#3     2     5
#4     2     6

Or if it doesn't needs to be group by

my_df %>%
   filter( (x == 1 & y == 1)|(x !=1))

Or with subset

subset(my_df,  (x == 1 & y == 1)|(x !=1))
#  x y
#1 1 1
#4 2 4
#5 2 5
#6 2 6

Or

subset(my_df,  (x == 1 & y == 1)|(x !=1 & y != 1))
Related