问题描述:

Suppose that I have a 90x4 matrix, say matrixgroup1, and some of rows are zero vectors. I want to find the rows that are not zero vectors. The code that I try was:

which(matrixgroup1[,1:4]!=c(0,0,0,0))

and it gave the result as

 [1] 1 9 19 28 59 60 62 91 99 109 118 149 150 152 181 189 199 208 239

[20] 240 242 271 279 289 298 329 330 332

However the right columns should be 1 9 19 28 59 60 62 . I don't know where the remaining 91-332 came from.

Since I am new to R, it's quite hard for me to figure it out. Can someone help me and give me the right code ? Thanks in advance.

网友答案:

Simply:

rowSums(matrixgroup1) != 0

网友答案:

I dont know, if it can be done better than this, but a solution would be to sum up each column seperately, and then check which of them is different from zero:

colcount<- ncol(matrixgroup1)
matrixgroup1NEW<-0
for(i in 1:colcount){
  matrixgroup1NEW[i]<-sum(matrixgroup1[,i])
}
which(matrixgroup1NEW!=0)

EDIT: thought you wanted which was zero. Changed to check which is nonzero

网友答案:

Creating a matrix with one "zero" row:

myMat <- cbind(x1 = c(1, 3, 8, 0, 1, 3), x2 = c(2, 4, 0, 0, 1, 0))

Getting the non-zero rows in the matrix:

myMat[which(!rowSums(myMat) == 0),]
相关阅读:
Top