Search code examples
rnansparse-matrix

Set all NaN elements in sparse matrix to zero


What's the equivalent of the Matlab statement X(isnan(X))=0 in R? Note X is of type of matrix.csr in R. (This is from pkg:SparseM.)


Solution

  • Are you sure you want to use the matrix.csr class? It is from the SparseM package and as far as I can tell, at least from the package documentation, there are no is.na<- or is.na[ methods. The Matrix-package does document is.na-methods:

    > library(Matrix);M <- Matrix(1:6, nrow=4, ncol=3,
    +        dimnames = list(c("a", "b", "c", "d"), c("A", "B", "C")))
    > stopifnot(all(!is.na(M)))
    > M[2:3,2] <- NA
    > M[is.na(M)] <- 0
    > M
    4 x 3 Matrix of class "dgeMatrix"
      A B C
    a 1 5 3
    b 2 0 4
    c 3 0 5
    d 4 2 6
    

    The Matrix package is now one of the recommended packages. My impression is that SparseM is not in widespread use.