我需要更新稀疏矩阵中的某些列,但该操作需要很长时间才能完成。
我有一个稀疏矩阵,行数略少于 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/