HaakonR
HaakonR

Reputation: 25

Delete rows with two conditions

My matrix in R:

"V1""V2""V3"
200 0.4  0.5
201 0.4  0.0
202 0.0  0.0
204 0.0  0.1

My goal is to only delete the rows where V2 AND V3 is zero, i.e row number 202. When I try

df[!(df[,2] == 0) & !(df[,3] == 0),]

It also removes 201 and 202.

Any help?

Thank you

Upvotes: 1

Views: 1575

Answers (1)

akrun
akrun

Reputation: 887981

The logic should be both 'V2' and 'V3' are zero then delete it. So, we need to use & for both 0 and then negate it to find only those rows that are not both 0

df[!(df[,2]==0 & df[,3]==0),]
#   V1  V2  V3
#1 200 0.4 0.5
#2 201 0.4 0.0
#4 204 0.0 0.1

This can be also done with rowSums

df[rowSums(df[,-1]!=0) >0,]

Upvotes: 1

Related Questions