I'd like to zero out the diagonal of a sparse matrix in R. My brute force way is explicitly setting it to zero, but this seems inefficient. Is there a more efficient way?
require(Matrix)
A <- as(rsparsematrix(nrow = 1e7, ncol = 1e7, nnz = 1e4), "sparseMatrix")
diag(A) <- 0
A <- drop0(A) # cleaning up
Clarification and resolution: my initial worry was that Matrix inflates the sparse matrix with actual zeros on the diagonal. This turns out not to be the case (in the end, although in the interim it is, see comment below). To see this, consider what would happen if we were to set the diagonal to one:
A <- as(rsparsematrix(nrow = 1e7, ncol = 1e7, nnz = 1e4), "sparseMatrix")
format(object.size(A), units = "Mb")
[1] "38.3 Mb"
diag(A) <- 1
format(object.size(A), units = "Mb")
[1] "152.7 Mb"
The many non-zero elements we have added use up O(n) memory, where n is the dim of the matrix. However, with diag(A) <- 0 we get:
diag(A) <- 1
format(object.size(A), units = "Mb")
[1] "38.3 Mb"
Namely, Matrix already handles this situation efficiently.