Reputation: 2593
I have very huge sparse matrix. I need to convert non-zero element of that matrix to 1 and other entries left zero. would someone help me to implement it in R ?
Upvotes: 0
Views: 2265
Reputation: 11
Using the sparse matrices from the Matrix
package, I tried both jbaums' and Julien's methods, but I would get the following error in both:
Error in if (any(i < 0L)) { : missing value where TRUE/FALSE needed
I found an alternative method that worked for me, and was very fast:
m <- as(m!= 0, "dMatrix")
m != 0
produces a lgCMatrix
, and converting it into a dgCMatrix
through the method above will change all the True
entries into 1, while leaving the False
entries sparse.
If you were wondering how I found this, a similar example was in the R documentation for lsparseMatrix-classes
.
Upvotes: 1
Reputation: 58
You could do
yourMatrix[which(yourMatrix != 0)] <- 1
(What @jbaums propose is also working)
Upvotes: 0