R过滤矩阵中的rownames

时间:2011-05-13 06:50:53

标签: r row dataframe

我有一个像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

现在我要删除所有值为零的所有行。结果将是:

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

谢谢!

2 个答案:

答案 0 :(得分:6)

使用all()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,]

结果:

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

答案 1 :(得分:3)

如果所有元素都是正数字,您可以使用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

这有点棘手,@ Vincent的方法更为通用。