开发者

R: how to merge two matrix according to their column and row names?

Input matrix A

       column1   column2   column3   column4
row1   0         1         0         0
row2   0         0         -1        0
row3   1         0         0         -1

Input matrix B

       column5   column6   column7   column8
row1   0         1         0         0
row2   0         0         -1开发者_如何学C        0
row4   1         0         0         -1

Output matrix 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

Remarks: matrix A and matrixB got overlapped row's name. However, all the columns' names are different.


You can use merge to do this by specifying the optional parameters by and 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)

Will yield

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

If you want to replace the NAs with zeros, this should work:

#Assign to an object
zz <- merge(dat1, dat2, by = "row.names", all = TRUE)
#Replace NA's with zeros
zz[is.na(zz)] <- 0
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜