如何在一个列表中的矩阵上使用 cbind 并将它们放在另一个列表中 (r)

How to use cbind on matrices in one list and place them in another (r)

我正在尝试连接存储在嵌套列表中的矩阵并将它们放在一个新列表中。例如,如果我有一个水果列表,我想获取存储在 Kiwi 下的各种矩阵,并将它们作为一个矩阵连接到一个新列表中。

这将生成类似于我的数据的内容:

#Define some important things
Fruits = c('Mango', 'Kiwi')
Attr = c('Size', 'Shape')

#generate empty lists
MyFruitList <- lapply(Fruits, function(q) {
  EmptySublist <- (setNames(vector("list", length(Fruits)), Attr))
})
names(MyFruitList) <- Fruits

#Full lists with example matrices
MyFruitList[['Mango']][['Size']] <- matrix(c(3,5,7,2), nrow=2, ncol=2)
MyFruitList[['Mango']][['Shape']] <- matrix(c(3,6,7,5), nrow=2, ncol=2)

MyFruitList[['Kiwi']][['Size']] <- matrix(c(1,3,4,2), nrow=2, ncol=2)
MyFruitList[['Kiwi']][['Shape']] <- matrix(c(2,4,5,1), nrow=2, ncol=2)

这是我一直试图用来将存储在 Kiwi 和 Mango 下的矩阵移动到新列表中的方法。

#Obviously this doesn't actually work
MyFruitListAsRows <- lapply(Fruits, function(i) {
  MyFruitListAsRows <- matrix(cbind(paste0(MyFruitList[i]))) 
})
names(MyFruitListAsRows) <- paste0(Fruits, "Row")

理想情况下,我应该得到一个名为 MyFruitsAsRows 的列表,其中包含名为 KiwiMango 的 2、4 x 2 矩阵,包含它们各自的 SizeShape 原始 MyFruitList 列表中的数据。

例如对于 Mango,它看起来像这样:

     [,1] [,2] [,3] [,4] 
[1,]    3    7   3    7
[2,]    5    2   6    5

(抱歉,数字过于相似,计划不周,一开始可能很难识别我希望我的数字去哪里)

由此构建:

$Size
     [,1] [,2]
[1,]    3    7
[2,]    5    2

$Shape
     [,1] [,2]
[1,]    3    7
[2,]    6    5

编辑:我尝试采纳 Ronak Shah 的建议并做了以下工作:

library(tidyverse)

MyFruitListAsRows <- map(MyFruitList[i], bind_cols)

但是运行,

MyFruitListAsRows[['KiwiRow']]
MyFruitListAsRows[['MangoRow']]

产生:

I get Error in x[i, , drop = FALSE] : subscript out of bounds

如果我尝试让 RStudio 向我显示 window 中的任一新列表中的内容,RStudio 会遇到致命错误并崩溃。

我们可以使用 base R 循环每个 MyFruitListcbind 它们 do.call

lapply(MyFruitList, function(x) do.call(cbind, x))

#$Mango
#     [,1] [,2] [,3] [,4]
#[1,]    3    7    3    7
#[2,]    5    2    6    5

#$Kiwi
#     [,1] [,2] [,3] [,4]
#[1,]    1    4    2    5
#[2,]    3    2    4    1

你也可以在这里使用cbind.data.frame


使用 tidyverse 我们可以 map 遍历每个列表然后 cbind

library(tidyverse)
map(MyFruitList, cbind.data.frame)

#$Mango
#  Size.1 Size.2 Shape.1 Shape.2
#1      3      7       3       7
#2      5      2       6       5

#$Kiwi
#  Size.1 Size.2 Shape.1 Shape.2
#1      1      4       2       5
#2      3      2       4       1