在R中设置稀疏矩阵的更快方法?

在R中设置稀疏矩阵的更快方法?,r,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

我试图在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))
库(矩阵)

f此代码运行速度快得多(我需要2.53秒…你的速度慢吗?这也就是我需要多长时间。问题是,除了其他操作之外,我还需要在模拟代码中执行100000次。>系统时间(应用(x,1,f))用户系统运行时间1.12 0.00 1.13瓶颈是
do.call
-是否有其他方法存储结果,或者您是否特别需要
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