R - I want to go through rows of a big matrix and remove all zeros

后端 未结 5 1109
星月不相逢
星月不相逢 2021-01-07 10:55

I have a lot of rows and columns in a very large matrix (184 x 4000, type double), and I want to remove all 0\'s. The values in the matrix are usually greater than 0 but the

5条回答
  •  清歌不尽
    2021-01-07 11:32

    I finally have the answer. The reason why

    x<- x[which(rowSums(x) > 0),]
    

    only returned 3 rows out of 184 was because this function only gives you those rows that do not sum up to 0 and/or do not have an NA in them. And I had a few NA's in all but 3 rows, I just wasn't aware of. Simply taking out the NA's did not work, because that didn't solve the rowSums problem. I needed the function to treat my NA's as zeros, so that the rows that did entail NA's (as in all but 3) would also be summed up and not just taken out of the matrix. So I turned all NA's into zeros by using

    x[is.na(x)] <- 0
    

    and THEN applying the function to sum up all rows and remove the ones that add up to 0. And it worked! Thanks to everyone for your input. Especially @arkun!

提交回复
热议问题