Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering out rows in a matrix containing only 0 in R

Tags:

r

matrix

I have the matrix

m <- matrix(c(1, 0, 3, 4, 0, 6), 3)

I need to filter out rows where both columns have a value of 0 in effect returning the matrix:

m <- matrix(c(1, 3, 4, 6), 3)

I have tried

m[m[, 1] > 0 & m[, 2] > 0]

but this returns a vector instead of a matrix stripped of rows with only 0. This should be simple but I am stuck.

Thanks, -Elizabeth

like image 288
Elizabeth Avatar asked Dec 19 '25 11:12

Elizabeth


2 Answers

In case you had many columns

m
     [,1] [,2]
[1,]    1    4
[2,]    0    0
[3,]    3    6
m^2
     [,1] [,2]
[1,]    1   16
[2,]    0    0
[3,]    9   36
rowSums(m^2)
[1] 17  0 45
m[rowSums(m^2)>0,]
     [,1] [,2]
[1,]    1    4
[2,]    3    6
like image 137
Julius Vainora Avatar answered Dec 22 '25 01:12

Julius Vainora


You are just missing a "," in your own solution. Use

m[m[,1]>0 & m[,2]>0,]

and it will work:

> m[m[,1]>0 & m[,2]>0,]
     [,1] [,2]
[1,]    1    4
[2,]    3    6
like image 32
BlueCoder Avatar answered Dec 22 '25 01:12

BlueCoder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!