cbind 列表列表的第二个元素

cbind 2nd element of list of lists together

我有像下面的 biglist 示例这样的数据,它是 2 个列表的列表,每个列表都是 2 个。我想 cbind 每个列表中的第二个列表在一起,就像下面的结果示例一样。通常,我会尝试 lapply(biglist,cbind) 之类的方法,但我不确定如何使用列表列表来做到这一点。

Data:
dput(biglist)
list(list(list(1, 2, 3), list(5, 4, 6)), list(list(5, 9, 2), 
list(4, 6, 1)))

Result:
dput(result)
structure(list(4, 6, 1, 5, 4, 6), .Dim = c(3L, 2L)

也许,像这样?

matrix(unlist(lapply(bigList, function(x) x[2])), ncol = length(bigList))

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

从每个列表中获取第二个元素,然后 unlisting 列表并将其转换为矩阵,其中列数 (ncol) 将是列表的 length .

有了 purrr,你可以做到

library(purrr)

bigList %>% map(2) %>% invoke(cbind, .)
##      [,1] [,2]
## [1,] 5    4   
## [2,] 4    6   
## [3,] 6    1 

或等效的基本 R:

do.call(cbind, lapply(bigList, `[[`, 2))
##      [,1] [,2]
## [1,] 5    4   
## [2,] 4    6   
## [3,] 6    1 

或者,这就是 sapply 简化的方式:

sapply(bigList, `[[`, 2)
##      [,1] [,2]
## [1,] 5    4   
## [2,] 4    6   
## [3,] 6    1 

不考虑语法的想法是提取每个子列表的第二个元素,然后将该列表作为参数传递给 cbind(好吧,实际上 simplify2arraysapply 中)。如果您希望按照预期的结果反转列,请在 cbind.

之前插入 rev

这是另一个版本mapply

mapply(`[[`, biglist, 2)
#   [,1] [,2]
#[1,] 5    4   
#[2,] 4    6   
#[3,] 6    1   

与 ronak-shah 的方法相关,您可以使用 vapply 来简化自动生成矩阵的输出。

vapply(bigList, function(i) unlist(i[[2]]), FUN.VALUE=numeric(3))
     [,1] [,2]
[1,]    5    4
[2,]    4    6
[3,]    6    1