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.
精彩评论