[英]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.