我有一个稀疏向量列表(在R中).我需要将此列表转换为稀疏矩阵.通过for循环执行它需要很长时间.
sm<-spMatrix(length(tc2),n.col)
for(i in 1:length(tc2)){
sm[i,]<-(tc2[i])[[1]];
}
Run Code Online (Sandbox Code Playgroud)
有没有更好的办法?
这是一个两步解决方案:
使用lapply()和as(..., "sparseMatrix")将sparseVectors列表转换为一列sparseMatrices的列表.
使用do.call()和cBind()将sparseMatrices组合在一个sparseMatrix中.
require(Matrix)
# Create a list of sparseVectors
ss <- as(c(0,0,3, 3.2, 0,0,0,-3), "sparseVector")
l <- replicate(3, ss)
# Combine the sparseVectors into a single sparseMatrix
l <- lapply(l, as, "sparseMatrix")
do.call(cBind, l)
# 8 x 3 sparse Matrix of class "dgCMatrix"
#
# [1,] . . .
# [2,] . . .
# [3,] 3.0 3.0 3.0
# [4,] 3.2 3.2 3.2
# [5,] . . .
# [6,] . . .
# [7,] . . .
# [8,] -3.0 -3.0 -3.0
Run Code Online (Sandbox Code Playgroud)