Emily
Emily

Reputation: 23

R matrix: How can I subset based on the sum across all columns?

I have a very large matrix, >30,000 elements. I would like to remove all rows that have a value of 0 across all column. After reading many posts, I think that parameters such as standard deviation=0 or the sum of the rows=0 would be appropriate to drop. I can't seem to figure out a working R code to do this. The subset command makes sense... I would appreciate any help or suggestions.

Another approach that may work:

I ran as.logical(rowSums(matrix !=0)) to return all of the rows that had values that were not 0, which worked. Is there another line that I can add in to create a new matrix with just the rows that returned TRUE?

Upvotes: 2

Views: 203

Answers (1)

akrun
akrun

Reputation: 887048

We can use rowSums on a logical matrix, create a logical vector and subset the rows of the matrix

m2 <- m1[!!rowSums(m1 != 0),]

data

m1 <- rbind(0, c(1, 3, 2), c(0, 1,2), c(4, 5, 2))

Upvotes: 1

Related Questions