Santhosh Subramanian
Santhosh Subramanian

Reputation: 125

How to edit this matrix R?

I have a matrix named dx:

     a b c d e f g h

cat  0 0 0 0 0 0 0 0 

dog  1 0 1 0 0 0 0 1

fish 1 1 1 0 0 0 0 0 

egg  0 0 0 0 0 0 0 0 

How do I delete the rows that goes all zero across like cat and egg. So that I can end up with this only -

     a b c d e f g h

dog  1 0 1 0 0 0 0 1

fish 1 1 1 0 0 0 0 0 

Upvotes: 1

Views: 77

Answers (2)

Andrelrms
Andrelrms

Reputation: 819

You can try something like this:

m<-matrix(c(1,1,1,0,
        0,0,0,0,
        1,0,1,0,
        0,0,0,0,
        1,1,1,1),ncol=4,byrow=T)
m[rowSums(abs(m))!=0,]

Upvotes: 2

scribbles
scribbles

Reputation: 4339

zeros_removed = apply(dx, 1, function(row) all(row !=0 ))
dx[zeros_removed,]

Upvotes: 0

Related Questions