我正在尝试连接存储在嵌套列表中的矩阵并将它们放在一个新列表中。例如,如果我有一个水果列表,我想在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
的列表,其中包含名为Kiwi
和Mango
的2,4 x 2矩阵,其中包含来自原始Size
列表的各自的Shape
和MyFruitList
数据。
例如对于芒果,它看起来像这样:
[,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向我展示窗口中任何一个新列表中的内容,那么RStudio会遇到致命错误并崩溃。
我们可以使用基数R循环每个MyFruitList
和cbind
他们与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