这段代码运行得更快(<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