Set all NaN elements in sparse matrix to zero

血红的双手。 提交于 2019-12-23 02:14:20

问题


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


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/28052861/set-all-nan-elements-in-sparse-matrix-to-zero

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!