Gongon
Gongon

Reputation: 505

How can I remove rows containing '0' of certain columns while keeping the rows IDs of remaining rows in R

I am trying to sort it out but could not able to do it. I want to get rid of all the rows with '0' values but keeping the ID numbers intact of remaining rows.

ID  B   C   D
1_2 34  42  12
1_3 34  32  2
1_4 0   0   0
1_5 12  33  12

output should be

ID  B   C   D
1_2 34  42  12
1_3 34  32  2
1_5 12  33  12

Upvotes: 5

Views: 14979

Answers (2)

fp4me
fp4me

Reputation: 463

if you want to remove the lines containing a 0 or many for column B,C or D :

DF[apply(DF[c(2:4)],1,function(z) !any(z==0)),] 

or only when all columns B,C,D contains 0 :

DF[apply(DF[c(2:4)],1,function(z) any(z!=0)),]

Upvotes: 7

S4M
S4M

Reputation: 4681

If tmp is the name of your original data.frame, the following works:

tmp2 <- data.frame(Reduce(rbind,apply(tmp,1,function(x){if(any(x==0)){NULL}else{x}})))

Upvotes: 1

Related Questions