首页 > 解决方案 > 按行名组合/匹配/合并向量

问题描述

我有一个变量名向量和几个单行矩阵。

我想创建一个新矩阵。新矩阵是通过将矩阵的行名与单行匹配/合并来创建的。

例子:

变量名向量

Complete_names <- c("D","C","A","B")

几个单行矩阵

Matrix_1 <- matrix(c(1,2,3),3,1)
rownames(Matrix_1) <- c("D","C","B")

Matrix_2 <- matrix(c(4,5,6),3,1)
rownames(Matrix_1) <- c("A","B","C")

期望的输出:

Desired_output <- matrix(c(1,2,NA,3,NA,6,4,5),4,2)
rownames(Desired_output) <- c("D","C","A","B")

 [,1] [,2]
D    1   NA
C    2    6
A   NA    4
B    3    5

我知道有几个类似的帖子,但这些以前的答案并不适合这个。

标签: r

解决方案


主要工作可以用 来完成merge,返回一个数据框:

merge(Matrix_1, Matrix_2, by = "row.names", all = TRUE)
#   Row.names V1.x V1.y
# 1         A   NA    4
# 2         B    3    5
# 3         C    2    6
# 4         D    1   NA

根据您的目的,您可以进一步修改名称或摆脱Row.names.


推荐阅读