从矩阵列表的列表中 rbind 矩阵 [英] rbind matrices from a list of a list of matrices

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

问题描述

我有一个list 矩阵的list.每个 list 具有相同数量的 matrices,其中每个 matrix 具有相同数量的列:

I have a list of a list of matrices. Each list has the same number of matrices where each matrix has the same number of columns:

set.seed(1)

mat.lol <- list(list1=list(matrix(rnorm(100),ncol=10),matrix(rnorm(200),ncol=10),matrix(rnorm(140),ncol=10)),
                list2=list(matrix(rnorm(80),ncol=10),matrix(rnorm(220),ncol=10),matrix(rnorm(110),ncol=10)),
                list3=list(matrix(rnorm(300),ncol=10),matrix(rnorm(500),ncol=10),matrix(rnorm(650),ncol=10)))

我想在所有列表中rbind每个matrix i 以便我最终得到这个list矩阵的code>:

And I'd like to rbind each matrix i across all lists so that I end up with this list of matrices:

mat.list <- list(rbind(mat.lol[[1]][[1]],mat.lol[[2]][[1]],mat.lol[[3]][[1]]),
                 rbind(mat.lol[[1]][[2]],mat.lol[[2]][[2]],mat.lol[[3]][[2]]),
                 rbind(mat.lol[[1]][[3]],mat.lol[[2]][[3]],mat.lol[[3]][[3]]))

实现这一目标的 apply function 是什么?

What would be the apply function that achieves that?

推荐答案

您可以使用 purrr 包中的 transpose() 函数来翻转列表 以便每个子列表都包含您想要绑定在一起的所有矩阵,然后您可以简单地遍历结果列表和 rbind 矩阵:

You can use transpose() function from purrr package to turn the list inside out so that each sub list contains all the matrices you want to bind together, and then you can simply loop through the result list and rbind the matrices:

library(purrr)
mat.list.1 <- lapply(transpose(mat.lol), do.call, what=rbind)

identical(mat.list, mat.list.1)
# [1] TRUE

<小时>

坚持使用 purrr 语法:

mat.list.3 <- transpose(mat.lol) %>% map(do.call, what=rbind)

identical(mat.list, mat.list.3)
# [1] TRUE

<小时>

或者你可以使用基础 R 中的 Map:

mat.list.2 <- do.call(Map, c(f = rbind, mat.lol))

identical(mat.list, mat.list.2)
# [1] TRUE

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

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