Remove row with condition in R

Viewed 98

I have a dataframe such as :

Col1 Col2 Col3
G1 0 1
G2 1 0
G3 2 1
G4 2 0
G5 0 2
G6 3 4

and I would like to remove row if:

  • the sum of Col2 and Col3 is 1
  • Col2 or Col3 contain one 0 value.

Here I should get:

Col1 Col2 Col3
G3 2 1
G6 3 4
1 Answers

You could use subset and include the condition.

subset(df, Col2 != 0 & Col3 != 0 & (Col2 + Col3) != (1- Col2))
#In this case this gives the same answer
#subset(df, Col2 != 0 & Col3 != 0)

#  Col1 Col2 Col3
#3   G3    2    1
#6   G6    3    4

Or using it in dplyr::filter

library(dplyr)
df %>% filter(Col2 != 0 & Col3 != 0 & (Col2 + Col3) != (1- Col2))

data

df <- structure(list(Col1 = structure(1:6, .Label = c("G1", "G2", "G3", 
"G4", "G5", "G6"), class = "factor"), Col2 = c(0L, 1L, 2L, 2L, 
0L, 3L), Col3 = c(1L, 0L, 1L, 0L, 2L, 4L)), class = "data.frame", 
row.names = c(NA, -6L))
Related