How to remove rows with 0 values using R

ivivek_ngs picture ivivek_ngs · Aug 5, 2013 · Viewed 35.2k times · Source

Hi am using a matrix of gene expression, frag counts to calculate differentially expressed genes. I would like to know how to remove the rows which have values as 0. Then my data set will be compact and less spurious results will be given for the downstream analysis I do using this matrix.

Input

gene    ZPT.1   ZPT.0   ZPT.2   ZPT.3   PDGT.1  PDGT.0
XLOC_000001 3516    626 1277    770 4309    9030
XLOC_000002 342 82  185 72  835 1095
XLOC_000003 2000    361 867 438 454 687
XLOC_000004 143 30  67  37  90  236
XLOC_000005 0   0   0   0   0   0
XLOC_000006 0   0   0   0   0   0
XLOC_000007 0   0   0   0   1   3
XLOC_000008 0   0   0   0   0   0
XLOC_000009 0   0   0   0   0   0
XLOC_000010 7   1   5   3   0   1
XLOC_000011 63  10  19  15  92  228

Desired output

gene    ZPT.1   ZPT.0   ZPT.2   ZPT.3   PDGT.1  PDGT.0
XLOC_000001 3516    626 1277    770 4309    9030
XLOC_000002 342 82  185 72  835 1095
XLOC_000003 2000    361 867 438 454 687
XLOC_000004 143 30  67  37  90  236
XLOC_000007 0   0   0   0   1   3
XLOC_000010 7   1   5   3   0   1
XLOC_000011 63  10  19  15  92  228

As of now I only want to remove those rows where all the frag count columns are 0 if in any row some values are 0 and others are non zero I would like to keep that row intact as you can see my example above.

Please let me know how to do this.

Answer

bartektartanus picture bartektartanus · Aug 5, 2013
df[apply(df[,-1], 1, function(x) !all(x==0)),]