我正在尝试使用 Matrix 包将两个不同大小的稀疏矩阵绑定在一起。绑定在行上,使用列名进行匹配。
表一:
ID | AAAA | BBBB |
------ | ------ | ------ |
XXXX | 1 | 2 |
Run Code Online (Sandbox Code Playgroud)
表 B:
ID | BBBB | CCCC |
------ | ------ | ------ |
YYYY | 3 | 4 |
Run Code Online (Sandbox Code Playgroud)
绑定表 A 和 B:
ID | AAAA | BBBB | CCCC |
------ | ------ | ------ | ------ |
XXXX | 1 | 2 | |
YYYY | | 3 | 4 |
Run Code Online (Sandbox Code Playgroud)
目的是将大量小矩阵插入到一个大矩阵中,以实现连续查询和更新/插入。
我发现Matrix或slam软件包都没有处理此问题的功能。
以前也有人问过类似的问题,但似乎没有找到解决方案:
帖子 1:in-r-when-using-named-rows-can-a-sparse-matrix-column-be- added-concatenated
帖子 2:按行名称绑定在一起的稀疏模型矩阵
关于如何解决它的想法将不胜感激。
此致,
弗雷德里克
对于我的目的(具有数百万行和数万列的非常稀疏的矩阵,超过 99.9% 的值是空的)这仍然太慢了。有效的是下面的代码 - 也可能对其他人有帮助:
merge.sparse = function(listMatrixes) {
# takes a list of sparse matrixes with different columns and adds them row wise
allColnames <- sort(unique(unlist(lapply(listMatrixes,colnames))))
for (currentMatrix in listMatrixes) {
newColLocations <- match(colnames(currentMatrix),allColnames)
indexes <- which(currentMatrix>0, arr.ind = T)
newColumns <- newColLocations[indexes[,2]]
rows <- indexes[,1]
newMatrix <- sparseMatrix(i=rows,j=newColumns, x=currentMatrix@x,
dims=c(max(rows),length(allColnames)))
if (!exists("matrixToReturn")) {
matrixToReturn <- newMatrix
}
else {
matrixToReturn <- rbind2(matrixToReturn,newMatrix)
}
}
colnames(matrixToReturn) <- allColnames
matrixToReturn
}
Run Code Online (Sandbox Code Playgroud)