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

后端 未结 1 1039
攒了一身酷
攒了一身酷 2021-02-01 10:35

Input matrix A

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


        
相关标签:
1条回答
  • 2021-02-01 11:10

    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 讨论(0)
提交回复
热议问题