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

时间:2012-05-30 18:30:33

标签: 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()输出非常混乱。我很感激您对如何加快速度提出的任何建议。

感谢您的时间。

1 个答案:

答案 0 :(得分:8)

这段代码的运行速度要快得多(&lt; 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