I have a huge sparse with all zeros and I would like to replace some of its cells to value 1 based on indices from another matrix
. Note that different cells will be replaced across columns and their indices
are provided. I tried this on a sample data, and its quite slow. My real data has 1E8 rows. Appreciate any suggestions.
library(Matrix)
library(microbenchmark)
microbenchmark(
m1={
n_row <- 8000
n_col <- 5000
# create a sparse matrix
df <- Matrix(data=0, nrow=n_row, ncol=n_col, sparse=TRUE)
# define indices to be replaced
ind_replace <- data.frame(R1=c(4000, 5000), R2=c(1200, 3500), R3=c(7200, 7900))
for (kk in 1:ncol(ind_replace)){
df[ind_replace[1,kk]:ind_replace[2,kk], kk] <- 1
}
}
)
Unit: milliseconds
expr min lq mean median uq max neval
m1 18.48567 19.84298 22.48396 20.05846 20.48897 139.8459 100