R - 更新非常大的稀疏矩阵中的列

标签 r matrix sparse-matrix

我需要更新稀疏矩阵中的某些列,但该操作需要很长时间才能完成。

我有一个稀疏矩阵,行数略少于 3M,列数大约为 1500。我还有一个具有相同行数的数据框,但只有 10 列。我想用 data.frame 中的值更新矩阵中的某些列索引。

我对普通矩阵执行此操作没有问题,但是当使用稀疏矩阵尝试时,即使是单列也需要花费亿万年的时间。

下面是我正在使用的代码,需要更改哪些内容才能有效运行?

library(Matrix)

x <- Matrix(0, nrow = 2678748, ncol = 1559, sparse = TRUE)
df <- data.frame(replicate(5,sample(0:1,2678748,rep = TRUE)))

var_nums <- sample(1:1559,size = 5)

for (i in 1:5){
  x[,var_nums[i]] <- df[,i]
}

最佳答案

使用 Matrix::cBind 函数并消除 for 循环,我能够在 1 秒内完成它。

library(Matrix)

x  <- Matrix(0, nrow = 2678748, ncol = 1559, sparse = TRUE)
df <- data.frame(replicate(5,sample(0:1,2678748,rep = TRUE)))

var_nums <- sample(1:1559,size = 5)

t <- Sys.time()
x            <- x[,-var_nums]
x            <- Matrix::cBind(x, Matrix::as.matrix(df))
Sys.time()-t
Time difference of 0.541054 secs

保留顺序(仍低于 1 秒!)

library(Matrix)

x  <- Matrix(0, nrow = 2678748, ncol = 1559, sparse = TRUE)
df <- data.frame(replicate(5,sample(0:1,2678748,rep = TRUE)))

colnames(x) <- paste("col", 1:ncol(x))
col.order   <- colnames(x)

cols <- sample(colnames(x),size = 5)
colnames(df) <- cols

t <- Sys.time()
x            <- x[,-which(colnames(x) %in% cols)]
x            <- Matrix::cBind(x, Matrix::as.matrix(df) )
x            <- x[,col.order]
Sys.time()-t
>     Time difference of 0.550012 secs

# Proof that order is preserved:
identical(colnames(x), col.order)

TRUE

关于R - 更新非常大的稀疏矩阵中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45988067/

相关文章:

json - 如何让 rjson 的 fromJSON 方法将 JSON NULL 转换为 R NA?

r - 在 R 中用于跟踪矩阵的函数是什么

arrays - 在大范围内解析为数组 VBA 的最有效方法

python-3.x - BicGStab 产生意外故障标志

r - 计算分组数据中各点之间的欧式距离

r - Rstudio 使用 igraph 的网络错误消息

r - 使 R 包在 Windows 和 Linux 中工作

Python 矩阵通过一列排序

javascript - 迭代稀疏数组

python - 数组与稀疏矩阵的相关性