简体   繁体   中英

R filter rownames in matrix

I have a dataframe like z:

z <- matrix(c(1,0,0,1,1,0,0,
          1,0,0,0,1,0,0,
          0,0,0,0,0,0,0,
          0,0,1,0,0,0,0),
        nrow=7,
        dimnames=list(LETTERS[1:7],NULL))

   [,1] [,2] [,3] [,4]
A    1    1    0    0
B    0    0    0    0
C    0    0    0    1
D    1    0    0    0
E    1    1    0    0
F    0    0    0    0
G    0    0    0    0

Now I want to remove all the rows where all the values are zero. Than the result will be:

   [,1] [,2] [,3] [,4]
A    1    1    0    0
C    0    0    0    1
D    1    0    0    0
E    1    1    0    0

Thanks!

Use all() and apply() :

z <- matrix(c(1,0,0,1,1,0,0,
          1,0,0,0,1,0,0,
          0,0,0,0,0,0,0,
          0,0,1,0,0,0,0),
        nrow=7,
        dimnames=list(LETTERS[1:7],NULL))

all.0 <- apply(z, 1, function(i) all(i==0))
z[!all.0,]

Result:

  [,1] [,2] [,3] [,4]
A    1    1    0    0
C    0    0    0    1
D    1    0    0    0
E    1    1    0    0

And also if all element is positive numeric, you can do by using rowSums :

> z[rowSums(z)>0,]
  [,1] [,2] [,3] [,4]
A    1    1    0    0
C    0    0    0    1
D    1    0    0    0
E    1    1    0    0

this is little bit tricky, and @Vincent's approach is more general.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM