r-在行上绑定大小不同的稀疏矩阵 [英] r - Binding sparse matrices of different sizes on rows
问题描述
我正在尝试使用Matrix包将两个大小不同的稀疏矩阵绑定在一起.绑定在行上,使用列名进行匹配.
I am attempting to use the Matrix package to bind two sparse matrices of different size together. The binding is on rows, using the column names for matching.
表A:
ID | AAAA | BBBB |
------ | ------ | ------ |
XXXX | 1 | 2 |
表B:
ID | BBBB | CCCC |
------ | ------ | ------ |
YYYY | 3 | 4 |
绑定表A和B :
ID | AAAA | BBBB | CCCC |
------ | ------ | ------ | ------ |
XXXX | 1 | 2 | |
YYYY | | 3 | 4 |
目的是在单个大矩阵中插入大量小矩阵,以实现连续查询和更新/插入.
The intention is to insert a large number of small matrices into a single large matrix, to enable continuous querying and update/inserts.
我发现 Matrix 或 slam 软件包都没有处理此问题的功能.
I find that neither the Matrix or slam packages have functionality to handle this.
过去曾问过类似的问题,但似乎没有找到解决办法:
Similar questions have been asked in the past, but it seems no solution has been found:
发布1:帖子2: bind-together-sparse-model-matrices-行名
有关如何解决该问题的想法将受到高度赞赏.
Ideas on how to solve it will be highly appreciated.
最诚挚的问候,
弗雷德里克
推荐答案
看起来有必要在矩阵中添加空列(具有0的列),以使它们与rbind
(具有相同列的矩阵)兼容名称,并且顺序相同).下面的代码可以做到这一点:
It looks it's necessary to have empty columns (columns with 0s) added to the matrices so to make them compatible for a rbind
(matrices with the same column names, and on the same order). The following code does it:
# dummy data
set.seed(3344)
A = Matrix(matrix(rbinom(16, 2, 0.2), 4))
colnames(A)=letters[1:4]
B = Matrix(matrix(rbinom(9, 2, 0.2), 3))
colnames(B) = letters[3:5]
# finding what's missing
misA = colnames(B)[!colnames(B) %in% colnames(A)]
misB = colnames(A)[!colnames(A) %in% colnames(B)]
misAl = as.vector(numeric(length(misA)), "list")
names(misAl) = misA
misBl = as.vector(numeric(length(misB)), "list")
names(misBl) = misB
## adding missing columns to initial matrices
An = do.call(cbind, c(A, misAl))
Bn = do.call(cbind, c(B, misBl))[,colnames(An)]
# final bind
rbind(An, Bn)
这篇关于r-在行上绑定大小不同的稀疏矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!