Ville
Ville

Reputation: 547

R: Removing zero rows from a matrix and keep the row indexes

I have this matrix:

      [,1]  [,2]  [,3]  [,4]
one   0e+00 0e+00 0e+00 0e+00
two   1e-05 2e-05 3e-05 4e-05
three 0e+00 0e+00 0e+00 0e+00
four  0e+00 0e+00 0e+00 0e+00

I want to remove all the zero rows and still leave it as a matrix, not a data frame, and keep the index two in this case, the output should be like this:

      [,1]  [,2]  [,3]  [,4]
two   1e-05 2e-05 3e-05 4e-05

Here is the code:

mat=matrix(c(0e+00,1e-05,0e+00,0e+00,0e+00,2e-05,0e+00,0e+00,0e+00,3e-05,0e+00,0e+00,0e+00,4e-05,0e+00,0e+00), nrow=4)
rownames(mat)= c("one", "two", "three", "four")
mat=mat[which(rowSums(mat) > 0),]

It removes all the zero rows, but instead of leaving the result as a matrix, it creates a list.

Upvotes: 0

Views: 223

Answers (2)

Gregor Thomas
Gregor Thomas

Reputation: 145765

Matrices of one row or column are by default turned into vectors by "dropping" the dimension attribute. You can stop this by adding the drop = FALSE argument to [.

mat=matrix(c(0e+00,1e-05,0e+00,0e+00,0e+00,2e-05,0e+00,0e+00,0e+00,3e-05,0e+00,0e+00,0e+00,4e-05,0e+00,0e+00), nrow=4)
rownames(mat) = c("one", "two", "three", "four")
mat = mat[which(rowSums(mat) > 0), , drop = FALSE]
mat
#      [,1]  [,2]  [,3]  [,4]
# two 1e-05 2e-05 3e-05 4e-05
class(mat)
# [1] "matrix"

Upvotes: 2

DCZ
DCZ

Reputation: 1744

Try this:

mat=matrix(c(0e+00,1e-05,0e+00,0e+00,0e+00,2e-05,0e+00,0e+00,0e+00,3e-05,0e+00,0e+00,0e+00,4e-05,0e+00,0e+00), nrow=4)
rownames(mat)= c("one", "two", "three", "four")
mat=mat[rowSums(mat==0) !=ncol(mat),]
mat

Upvotes: 0

Related Questions