R:如何根据列名和行名合并两个矩阵? [英] R: how to merge two matrix according to their column and row names?

查看:2155
本文介绍了R:如何根据列名和行名合并两个矩阵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

输入矩阵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的行名称重叠.但是,所有列的名称都不同.

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

推荐答案

您可以使用merge通过指定可选参数byall来做到这一点:

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)

会产量

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替换为零,这应该可以:

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

这篇关于R:如何根据列名和行名合并两个矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆