user18441
user18441

Reputation: 663

how to eliminate the rows of a matrix matching certain conditions? in R

I've got this matrix:

mm <- matrix(c(1,2,0,0,3,0,0,0,3,4,0,2,2,0,1,0,2,0,0,0,2,0,0,2,0,0,1,0,0,1,0,2,0,1,0,3,0,2,0,3),10,4)

and I would like to eliminate all those rows in which only one of the elements is different of 0, for example: 3 0 0 0 or 0 2 0 0, but I would like to keep those rows with more than one element different of 0, as 3 1 0 0.

any help on this would be very appreciated.

Tina.

Upvotes: 2

Views: 89

Answers (1)

eddi
eddi

Reputation: 49448

mm[rowSums(mm != 0) > 1,]
#     [,1] [,2] [,3] [,4]
#[1,]    1    0    2    0
#[2,]    2    2    0    2
#[3,]    0    0    2    1
#[4,]    3    1    0    0
#[5,]    0    2    1    0
#[6,]    4    0    1    3

Upvotes: 2

Related Questions