user1631306
user1631306

Reputation: 4470

conditional removal from data frame

I have a data frame

r <- data.frame("a" = c(1,2,2,0,0,3,0,3),"b"=c("a","b","c","a","a","c","d","d"))

#   a b
# 1 1 a
# 2 2 b
# 3 0 c
# 4 0 a
# 5 0 a
# 6 3 c
# 7 0 d
# 8 3 d

I want to make subset of above data frame, which should follow the given criteria

i want to keep all the rows which 1. r$a !=0, 2. but for the rows r$a==0, if r$b=="a", then keep it

I tried to do r[!(r$a==0),], but thats for first condition only, how would i put second condition.

Output would be

#   a b
# 1 1 a
# 2 2 b
# 3 0 a
# 4 0 a
# 5 3 c
# 6 3 d

Upvotes: 2

Views: 78

Answers (2)

entropium
entropium

Reputation: 29

Have you tried this?

r[!(r$a == 0) | r$b == "a", ]

Upvotes: 0

Sam Dickson
Sam Dickson

Reputation: 5239

Use this:

r[r$a!=0 | (r$a==0 & r$b=="a"),]

Alternatively, you can just use:

r[r$a!=0 | r$b=="a",]

Upvotes: 4

Related Questions