ajmartin
ajmartin

Reputation: 2409

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.)

Upvotes: 1

Views: 2208

Answers (2)

IRTFM
IRTFM

Reputation: 263481

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.

Upvotes: 1

W7GVR
W7GVR

Reputation: 2000

The function in R is actually is.na.

Then you can use logical indexing just like you use in Matlab (only being careful to use square brackets):

X[is.na(X)]=0

Upvotes: 0

Related Questions