开发者

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

开发者 https://www.devze.com 2023-02-27 05:46 出处:网络
Input matrix A column1column2column3column4 row10100 row200-10 row3100-1 Input matrix B column5column6column7column8

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

精彩评论

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