Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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
like image 294
Gongon Avatar asked Sep 05 '12 11:09

Gongon


2 Answers

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)),]
like image 88
fp4me Avatar answered Nov 01 '22 17:11

fp4me


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}})))
like image 28
S4M Avatar answered Nov 01 '22 15:11

S4M