从稀疏向量列表创建稀疏矩阵 [英] Creating sparse matrix from a list of sparse vectors
本文介绍了从稀疏向量列表创建稀疏矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个稀疏向量的列表(在R中).我需要将此列表转换为稀疏矩阵. 通过for循环完成此过程需要很长时间.
I have a list of sparse vectors (in R). I need to convert this list to a sparse matrix. Doing it via a for-loop takes a long time.
sm<-spMatrix(length(tc2),n.col)
for(i in 1:length(tc2)){
sm[i,]<-(tc2[i])[[1]];
}
有更好的方法吗?
推荐答案
以下是两步解决方案:
-
使用
lapply()
和as(..., "sparseMatrix")
将 sparseVectors 的列表转换为一列 sparseMatrices 的列表.
Use
lapply()
andas(..., "sparseMatrix")
to convert the list of sparseVectors to a list of one column sparseMatrices.
使用do.call()
和cBind()
将 sparseMatrices 组合到单个 sparseMatrix 中.
Use do.call()
and cBind()
to combine the sparseMatrices in a single 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
这篇关于从稀疏向量列表创建稀疏矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文