0

Is there a way to delete rows based on values . For example

df
ColA   ColB
A      1
B      2    
A      3

Expected output (Basically i know we can delete based on row number. But is there way to way to delete based on values ("A", 3)

df
ColA   ColB
A      1
B      2    
user11740857
  • 141
  • 7
  • check out the [`subset`](https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/subset) function `subset(df, !(ColA == "A" & ColB == 3))` – bouncyball Feb 09 '21 at 14:33

3 Answers3

1

You can use subset from base R

> subset(df,!(ColA=="A"&ColB==3))
  ColA ColB
1    A    1
2    B    2

or a data.table solution

> setDT(df)[!.("A",3),on = .(ColA,ColB)]
   ColA ColB
1:    A    1
2:    B    2
ThomasIsCoding
  • 53,240
  • 4
  • 13
  • 45
1

An option with filter

library(dplyr)
df %>% 
    filter(!(ColA == "A" & ColB == 3))
   
akrun
  • 674,427
  • 24
  • 381
  • 486
0

The easiest way to do this is to use the which() function (?which). You can then use this with a minus sign in conjunction with with indexing to subset based on a particular criteria.

df <- as.data.frame(cbind("ColA"=c("A", "B", "A"), "ColB" = c(1, 2, 3)))

df <- df[-which(df[,2]==3),]

View(df)
aromatic6tet
  • 81
  • 1
  • 8