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

后端 未结 5 1077
星月不相逢
星月不相逢 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:36

    You can drop rows which only contain 0s like this (and you could replace 0 with any other number if you wanted to drop rows with only that number):

    x <- x[rowSums(x == 0) != ncol(x),]
    

    Explanation:

    • x == 0 creates a matrix of logical values (TRUE/FALSE) and rowSums(x == 0) sums them up (TRUE == 1, FALSE == 0).
    • Then you check if the sum of each row is not equal to the number of columns of your matrix (which are counted by ncol(x)).
    • If that is the case (which means not all entries are 0s), the row will be kept because it evaluates to TRUE. All other rows evaluate to FALSE and will be dropped.

提交回复
热议问题