我有一个 R 矩阵列表。每个矩阵都有行和列名称 - 有时与列表中其他矩阵中的其他行和列名称重叠。例如
Mat1 <- as.matrix( read.table(text="Col1 Col2 Col3
Row1 0 0 0
Row2 1 0 5
Row3 5 2 0", head=TRUE))
Mat2<- as.matrix( read.table(text="Col1 Col3 Col4
Row2 0 0 0
Row3 1 0 5
Row4 5 2 0",head=TRUE))
如何组合列表中的所有矩阵,以便 (1)行和列相交的地方,数字相加? (2) 当行和列不相交时,原始矩阵的值被保留?
我在网上找到的所有示例(例如使用“合并”功能)都只关注列合并或行合并。
编辑: 正如许多人指出的那样,我没有在代码中提供可重现的示例 - 使用“dput”函数在下面添加
list(structure(c(0, 1, 5, 0, 0, 2, 0, 5, 0), .Dim = c(3L, 3L), .Dimnames = list(
c("Row1", "Row2", "Row3"), c("Col1", "Col2", "Col3"))), structure(c(0,
1, 5, 0, 0, 2, 0, 5, 0), .Dim = c(3L, 3L), .Dimnames = list(c("Row2",
"Row3", "Row4"), c("Col1", "Col3", "Col4"))))
最佳答案
##
# this is a minimal reproducible example
# ### YOU should provide this ###
#
m1 <- matrix(c(0,0,0,1,0,5,5,2,0), nc=3, byrow = TRUE,
dimnames = list(c('row.1', 'row.2', 'row.3'), c('col.1', 'col.2', 'col.3')))
m2 <- matrix(c(0,0,0,1,0,5,5,2,0), nc=3, byrow = TRUE,
dimnames = list(c('row.2', 'row.3', 'row.4'), c('col.1', 'col.3', 'col.4')))
##
# you start here
#
library(data.table)
m <- rbind(melt(as.data.table(m1, keep.rownames = T), id='rn'),
melt(as.data.table(m2, keep.rownames = T), id='rn'))
m[is.na(value), value:=0]
dcast(m, rn~variable, fun.aggregate = sum)
## rn col.1 col.2 col.3 col.4
## 1: row.1 0 0 0 0
## 2: row.2 1 0 5 0
## 3: row.3 6 2 0 5
## 4: row.4 5 0 2 0
关于r - R中有没有一种方法可以按行和列组合不同大小的矩阵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72156627/