mercredi 26 juillet 2017

Replace row values if sum is equal to zero in R

I want to replace the values of columns by NA if the sum of their rows is equal to 0. Imagine the following columns:

a b 
0 0
1 5
2 8
3 7
0 0
5 8 

I would like to replace these by:

a b 
NA NA
1 5
2 8
3 7
NA NA
5 8 

I've been looking for answers on many pages but have not found any solution.

Here is what I have tried so far:

df[ , 31:36][df[,31:36] == 0 ] <- NA    #With df being my dataframe and 31:36 the columns I want to apply the replacement too. 

This replaces all the values equal to 0 by NA

I've also tried other alternatives using rowSums() but have not found a solution.

Any help would be greatly appreciated.

Thanks

Aucun commentaire:

Enregistrer un commentaire