Search code examples
rfilterdelete-row

Delete rows referring values in two columns in R


I have a data frame with 8 columns. I want to remove the rows of data from the data frame when column named "iterator" takes a value of 5 and column named "hdway" has value >10. The first few rows of the dataframe DF is given below.

   iterator hdway CV beta spacing      OC       UC ID
1         5     5  0    0     0.1 2.50468 95.22558  1
2         5     5  0    0     0.1 2.50468 95.22558  2
3         5     5  0    0     0.1 2.50468 95.22558  3
4         5     5  0    0     0.1 2.50468 95.22558  4
5         5     5  0    0     0.1 2.50468 95.22558  5
6         5     5  0    0     0.1 2.50468 95.22558  6
7         5     5  0    0     0.1 2.50468 95.22558  7
8         5     5  0    0     0.1 2.50468 95.22558  8
9         5     5  0    0     0.1 2.50468 95.22558  9
10        5     5  0    0     0.1 2.50468 95.22558 10

What I have tried:

df <- DF %>% filter(DF$iterator == 5 & DF$value <= 10)

The above code returns me a subset of data frame, DF only with iterator =5 and value<=10.


Solution

  • We can negate (!) the logical expression (iterator ==5 & hdway > 10) to remove those rows where the 'iterator' is 5 and hdway greater than 10

    df <- DF %>%
                filter(! (iterator == 5 & hdway > 10))
    

    NOTE: We don't need the DF$ inside the tidyverse functions