0

Dataframe:

A ; B
x   1
x   7
y   2
y   3
z   9
z   1

I want to remove all rows where A=x and A=z because x and z have value 1 in column B. Therefore, the dataframe must look like this:

A ; B
y   2
y   3

Thanks,

savioecon
  • 31
  • 3
  • 1
    See: [Remove multiple rows if condition for one row is met](https://stackoverflow.com/q/66531815/10488504) – GKi Mar 11 '21 at 12:38

3 Answers3

1

You can try subset

> subset(df, ! A %in% c("x","z"))
  A B
3 y 0
4 y 0

data

> dput(df)
structure(list(A = c("x", "x", "y", "y", "z", "z"), B = c(1L, 
0L, 0L, 0L, 0L, 1L)), class = "data.frame", row.names = c(NA,
-6L))
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
  • Thanks for your answer. My df has thousands of rows, so I want to remove the rows based on column B values. – savioecon Mar 11 '21 at 12:54
0
my.data.frame <- subset(data , A != "x" | A != "z")

Btw, duplicate of How to combine multiple conditions to subset a data-frame using "OR"?

vojtam
  • 1,157
  • 9
  • 34
0

a data.table approach

library( data.table )
DT <- fread("A  B
x   1
x   7
y   2
y   3
z   9
z   1")


DT[ copy(DT)[, temp := sum(B == 1), by = A ]$temp == 0, ]

#    A B
# 1: y 2
# 2: y 3
Wimpel
  • 26,031
  • 1
  • 20
  • 37
  • Thanks for your answer. Column B does not always have 1 or 0 values. I want to remove all rows in column A that at least once have a value of 1 in column B. – savioecon Mar 11 '21 at 13:04
  • see updated answer.. also, if B has other values than 0 or 1, you should probably add some in your sample data.. – Wimpel Mar 11 '21 at 13:09
  • Thanks a lot. Now my question is more like my real base. – savioecon Mar 11 '21 at 13:17