Search code examples
rdplyrfilter

Remove rows with dplyr based on two conditions of two variables in R


I have a dataframe

day<-c(155, 155, 155, 155, 155, 155, 155, 155, 155, 156, 156, 156, 156, 156, 156, 156, 156,
       156, 157, 157, 157, 157, 157, 157, 157, 157, 157)
id<-c(149, 188, 206, 224, 151, 166, 186, 210, 226, 149, 188, 206, 224, 151, 166, 186, 210, 226, 149, 188,
      206, 224, 151, 166, 186, 210, 226)
var<-c(7.85481, 13.90381, 19.47181, 16.85981,  9.41781,  9.11281, 16.62381, 20.00081, 18.57781,  7.41781, 13.71681,
       20.21881, 17.73281,  7.29281,8.48781, 18.49481, 20.74881 ,19.13781 ,10.60381 ,17.51981 , 2.67881 ,18.29481, 10.60381 ,
       1.79581, 22.11081,  2.82081, 21.81281)
df<-data_frame(day,id,var)

df
> df
# A tibble: 27 × 3
     day    id   var
   <dbl> <dbl> <dbl>
 1   155   149  7.85
 2   155   188 13.9 
 3   155   206 19.5 
 4   155   224 16.9 
 5   155   151  9.42
 6   155   166  9.11
 7   155   186 16.6 
 8   155   210 20.0 
 9   155   226 18.6 
10   156   149  7.42
# ℹ 17 more rows
# ℹ Use `print(n = ...)` to see more rows

From which I need to remove rows based on two conditions:

I need to remove the day 157 of id 166, the day 157 of id 206 and the day 157 of id 210.

I tried the following:

    df%>%
    filter(!id==166 & !day==157,
              !id==206 & !day==157,
              !id==210 & !day==157)
    # A tibble: 12 × 3
         day    id   var
       <dbl> <dbl> <dbl>
     1   155   149  7.85
     2   155   188 13.9 
     3   155   224 16.9 
     4   155   151  9.42
     5   155   186 16.6 
     6   155   226 18.6 
     7   156   149  7.42
     8   156   188 13.7 
     9   156   224 17.7 
    10   156   151  7.29
    11   156   186 18.5 
    12   156   226 19.1 

> 

But that removes all rows of day 157

How can I combine both conditions?

Thanks in advance!


Solution

  • Option 1:

    df %>%
      filter(!(id==166 & day==157),
             !(id==206 & day==157),
             !(id==210 & day==157)) 
    

    Option 2:

    '%!in%' <- Negate(`%in%`)
    df %>% 
      filter( id %!in% c(166,206,210) | day != 157)