本文介绍了R中的粘贴矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对粘贴矩阵有疑问.我有一组10个矩阵,它们具有相同的行名但具有不同的列名,例如

I have a question regarding pasting matrices. I have a set of 10 matrices with the same row name but different column names, e.g.

矩阵1:

   A B C D
a  1 0 0 0
b  0 1 0 0
c  0 1 0 0
d  0 0 1 0
e  0 0 0 1

矩阵2:

  A B D E F
a 1 0 0 0 0
b 0 1 0 0 0
c 0 1 0 0 0
d 0 0 0 0 0
e 0 0 1 0 0

我想将两个矩阵的格式设置为

I would like to format both matrices as

  A B C D E F
a 1 0 0 0 0 0
b 0 1 0 0 0 0
c 0 1 0 0 0 0
d 0 0 1 0 0 0
e 0 0 0 1 0 0

如何在R中快速执行而不循环?谢谢!

How can I do it quickly in R without looping?Thanks!

推荐答案

示例数据:

mat1 <- data.matrix(read.table(text="A B C D
a  1 0 0 0
b  0 1 0 0
c  0 1 0 0
d  0 0 1 0
e  0 0 0 1", header = TRUE, row.names = 1))

mat2 <- data.matrix(read.table(text="A B D E F
a 1 0 0 0 0
b 0 1 0 0 0
c 0 1 0 0 0
d 0 0 0 0 0
e 0 0 1 0 0", header = TRUE, row.names = 1))

假设您将所有矩阵都放在一个列表中(如果没有,请创建一个)

Let's assume you have all your matrices in a list (if not, create one)

mat.list <- list(mat1, mat2)

我们的第一步是将矩阵转换为data.frames.这将使算法有效利用内存:

Our first step is to convert the matrices to data.frames. This will make the algorithm make an efficient use of memory:

df.list <- lapply(mat.list, as.data.frame)

我们编写了一个合并两个data.frames的函数:

We write a function to merge two data.frames:

cat.df <- function(d1, d2) {d1[names(d2)] <- d2; d1}

我们迭代地将所有data.frame合并为一个大data.frame:

We merge all the data.frames iteratively, into one big data.frame:

one.df <- Reduce(cat.df, df.list)

最后,我们将其转换为矩阵:

Finally, we convert it to a matrix:

one.mat <- data.matrix(one.df)

这篇关于R中的粘贴矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 17:58