输入矩阵A
column1 column2 column3 column4
row1 0 1 0 0
row2 0 0 -1 0
row3 1 0 0 -1
输入矩阵B
column5 column6 column7 column8
row1 0 1 0 0
row2 0 0 -1 0
row4 1 0 0 -1
输出矩阵C
column1 column2 column3 column4 column5 column6 column7 column8
row1 0 1 0 0 0 1 0 0
row2 0 0 -1 0 0 0 -1 0
row3 1 0 0 -1 0 0 0 0
row4 0 0 0 0 1 0 0 -1
备注:矩阵A和矩阵B重叠了行的名称。但是,所有列的名称都不同。
答案 0 :(得分:20)
您可以使用merge
通过指定可选参数by
和all
来执行此操作:
#Reading data
txt1 <- "column1 column2 column3 column4
row1 0 1 0 0
row2 0 0 -1 0
row3 1 0 0 -1
"
txt2 <- "column5 column6 column7 column8
row1 0 1 0 0
row2 0 0 -1 0
row4 1 0 0 -1
"
dat1 <- read.table(textConnection(txt1), header = TRUE)
dat2 <- read.table(textConnection(txt2), header = TRUE)
#Merge them together
merge(dat1, dat2, by = "row.names", all = TRUE)
将产生
Row.names column1 column2 column3 column4 column5 column6 column7 column8
1 row1 0 1 0 0 0 1 0 0
2 row2 0 0 -1 0 0 0 -1 0
3 row3 1 0 0 -1 NA NA NA NA
4 row4 NA NA NA NA 1 0 0 -1
如果你想用零替换NA,这应该有效:
#Assign to an object
zz <- merge(dat1, dat2, by = "row.names", all = TRUE)
#Replace NA's with zeros
zz[is.na(zz)] <- 0