[英]Faster way to set up a sparse matrix in R?
我正在尝试在R中设置一种特殊的稀疏矩阵。下面的代码给出了我想要的结果,但速度非常慢:
library(Matrix)
f <- function(x){
out <- rbind(head(x, -1), tail(x, -1))
out <- bdiag(split(out, col(out)))
return(out)
}#END f
x <- outer(1:250, (1:5)/10, '+')
do.call(rBind, apply(x, 1, f))
在我正在进行的模拟研究中,我需要做成千上万次,所以这是一个相当严重的瓶颈。 在这种情况下,Rprof()输出非常混乱。 我很感激您对如何加快速度提出的任何建议。
感谢您的时间。
这段代码的运行速度要快得多(<0.01秒,相比我的盒子里的3.36秒),因为它避免了所有极慢的rBind
。 关键是首先准备行索引,列索引和非零单元格的值。 对sparseMatrix(i,j,x)
的单次调用将构造稀疏矩阵,甚至不需要对rBind()
进行一次调用。
library(Matrix)
A <- 1:250
B <- (1:5)/10
x <- outer(A, B, '+')
f2 <- function(x){
n <- length(x)
rep(x, each=2)[-c(1, 2*n)]
}
system.time({
val <- as.vector(apply(x,1,f2))
n <- length(val)
i <- seq_len(n)
j <- rep(rep(seq_len(length(B)-1), each=2), length.out=n)
outVectorized <- sparseMatrix(i = i, j = j, x = val)
})
# user system elapsed
# 0 0 0
只是为了表明结果是一样的:
## Your approach
f <- function(x){
out <- rbind(head(x, -1), tail(x, -1))
out <- bdiag(split(out, col(out)))
return(out)
}
system.time(outRBinded <- do.call(rBind, apply(x, 1, f)))
# user system elapsed
# 3.36 0.00 3.36
identical(outVectorized, outRBinded)
# [1] TRUE
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.