交错存储在R中的列表中的矩阵行 [英] interleave rows of matrix stored in a list in R
本文介绍了交错存储在R中的列表中的矩阵行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从矩阵列表中创建交错矩阵.
I want to create interleaved matrix from a list of matrices.
示例输入:
> l <- list(a=matrix(1:4,2),b=matrix(5:8,2))
> l
$a
[,1] [,2]
[1,] 1 3
[2,] 2 4
$b
[,1] [,2]
[1,] 5 7
[2,] 6 8
预期输出:
1 3
5 7
2 4
6 8
我已经检查了gdata中的interleave函数,但是它没有显示列表的这种行为.任何帮助表示赞赏.
I have checked the interleave function in gdata but it does not show this behaviour for lists. Any help appreciated.
推荐答案
这里是单线:
do.call(rbind, l)[order(sequence(sapply(l, nrow))), ]
# [,1] [,2]
# [1,] 1 3
# [2,] 5 7
# [3,] 2 4
# [4,] 6 8
为帮助理解,首先将矩阵与do.call(rbind, l)
堆叠在一起,然后以正确的顺序提取行:
To help understand, the matrices are first stacked on top of each other with do.call(rbind, l)
, then the rows are extracted in the right order:
sequence(sapply(l, nrow))
# a1 a2 b1 b2
# 1 2 1 2
order(sequence(sapply(l, nrow)))
# [1] 1 3 2 4
它将适用于任意数量的矩阵,并且即使行数不相同,它也会做正确的事情"(主观).
It will work with any number of matrices and it will do "the right thing" (subjective) even if they don't have the same number of rows.
这篇关于交错存储在R中的列表中的矩阵行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文