【问题标题】:How to efficiently assign values to a huge sparse matrix in R如何有效地将值分配给R中的巨大稀疏矩阵
【发布时间】:2017-09-16 16:21:30
【问题描述】:

我有一个非常稀疏的全零,我想根据另一个 matrix 的索引将它的一些单元格替换为值 1。请注意,将跨列替换不同的单元格,并提供它们的indices。我在一个样本数据上试过这个,而且速度很慢。我的真实数据有 1E8 行。感谢任何建议。

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

【问题讨论】:

  • (1) 为什么使用data.frame 将范围极值存储在各个列中?这看起来很奇怪且不可扩展,我会使用matrix(小写“m”)或列表,具体取决于您如何得出范围。 (2) 您的基准包括Matrixsequences 的创建,因此您不是在衡量只是价值替换。 (3) 你在这里争论几毫秒,你需要优化到这个程度的真正问题有多大或多复杂?
  • @r2evans,真正问题的矩阵在 1e8*5e3 级别,对于每一列,我需要将至少 80000 行替换为 1,这非常慢。为了演示,我创建了这个示例。
  • @tao.hong 一旦你生成了一系列你想要等于 1 的索引,试试这个解决方案:stackoverflow.com/questions/44692603/…
  • 另外,在您提供的示例中,您正在尝试访问超出矩阵大小的列索引。 df[,7200] 不存在。
  • l = lapply(ind_replace, function(x) x[1]:x[2]) ; n = lengths(l) ; sparseMatrix(i=unlist(l), j=rep(seq_len(ncol(ind_replace)), times=n), x=1, dims=c(n_row, n_col)) 加快了速度

标签: r matrix datatable sparse-matrix


【解决方案1】:

在从 ind_replace 中排除 R3 =c(7200,7900) 后尝试此操作,因为您正在创建的矩阵中不存在这些列:

library(Matrix)
n_row <- 8000
n_col <- 5000
ind_replace = data.frame(R1=c(4000, 5000), R2=c(1200, 3500))
spmat<-Matrix(0,nrow = n_row ,ncol = n_col,sparse = T)

创建一个矩阵ind,其中包含非零元素的行和列索引。

ind = apply(ind_replace,MARGIN = 2,function(t){data.frame(a= t[1]:t[2],b= t[1])})
ind = as.matrix(Reduce(function(x,y){rbind(x,y)},ind))
spmat[ind]=1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-01
    • 2020-12-07
    • 1970-01-01
    • 1970-01-01
    • 2019-05-26
    • 1970-01-01
    • 2020-07-30
    相关资源
    最近更新 更多