如何在R中合并具有重复尺寸的两个矩阵?

问题描述 投票:-1回答:1

我有两个矩阵,一个是跟随,

enter image description here

enter image description here

另一个是

enter image description here

enter image description here

如何基于它们的低位和列名(键)合并两个矩阵?

我尝试了以下代码,

merged_matrix <- merge(matrix1, matrix2, by.x = "row.names", all = TRUE)

但它没有合并,两个矩阵,只需添加更多这样的列,

enter image description here

enter image description here

r matrix merge
1个回答
0
投票

您可以像计划的那样使用合并合并矩阵。首先,如果要按列名进行合并,则需要使用可访问列名的内容。只需引用您感兴趣的矩阵和列名称(而不是rownames),它就是顺利航行(参见下面的示例代码)。

干杯,

m1 = round(matrix(c(rnorm(9, mean = 2)), nrow = 3, ncol = 3), digits = 2)
m2 = round(matrix(c(rnorm(9, mean = 2)), nrow = 3, ncol = 3), digits = 2)

colnames(m1) <- c(letters[1:3])
colnames(m2) <- rev(colnames(m1))

merge(m1,m2, by.x = colnames(m1), all = TRUE)

# > print(m1)
#       a    b    c
# [1,]  1.31 3.27 2.73
# [2,] -0.57 2.35 1.61
# [3,]  0.70 3.10 0.77
#
# > print(m2)
#       c    b    a
# [1,] -0.58 1.62 1.11
# [2,]  2.34 3.22 4.40
# [3,]  1.26 1.19 1.88
#  
# > merge(m1,m2, by.x = colnames(m1), all = TRUE)
#     a    b     c
# 1 -0.57 2.35  1.61
# 2  0.70 3.10  0.77
# 3  1.11 1.62 -0.58
# 4  1.31 3.27  2.73
# 5  1.88 1.19  1.26
# 6  4.40 3.22  2.34
© www.soinside.com 2019 - 2024. All rights reserved.