Bing
Bing

Reputation: 57

How to delete rows based on OR and AND conditions in r

I want to delete rows that have ID=3 but GENDER not equal to "F".

df<-data_frame(ID=c(2,3,3,3,3,5,6,7,8,9),GENDER=c("M","M","F","F","F","M","F","F","M","F"))

Upvotes: 0

Views: 33

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 388862

Another way to phrase the condition is to select rows where ID not equal to 3 or GENDER = 'F'.

subset(df, ID != 3 | GENDER == 'F')

#    ID GENDER
#  <dbl> <chr> 
#1     2 M     
#2     3 F     
#3     3 F     
#4     3 F     
#5     5 M     
#6     6 F     
#7     7 F     
#8     8 M     
#9     9 F     

and with dplyr filter :

dplyr::filter(df, ID != 3 | GENDER == 'F')

Upvotes: 0

akrun
akrun

Reputation: 887018

We can create a logical expression in filter and negate (!) the whole to remove those rows

library(dplyr)
df %>%
       filter(!(ID == 3 & GENDER != "F"))

or the same with subset from base R

subset(df, !(ID == 3 & GENDER != "F"))

Upvotes: 2

Related Questions