[英]Combine rows within the same list of a list
I have a list that contains two lists in which the first has three elements and the second has two elements.我有一个包含两个列表的列表,其中第一个包含三个元素,第二个包含两个元素。 I want to row combine the elements from the same list.
我想将同一列表中的元素组合起来。 Here are some data:
以下是一些数据:
list1 <- list(a = c(1,2,3), b = c(4,5,6)) #the first nested list which has three elements
list2 <- list(a = c(2,4), b = c(5,6)) #the second nested list which has two elements
alllist<- list(list1, list2) #the combo list that nests list1 and list2
In the end, I simply convert alllist
to a list that looks like this:最后,我简单地将
alllist
转换为如下所示的列表:
[[1]]
[1] 1 2 3
[1] 4 5 6
[[2]]
[1] 2 4
[1] 5 6
A purrr::map
and dplyr::bind_rows
based approach, which was inspired by @akrun first solution:一种
purrr::map
和dplyr::bind_rows
的方法,其灵感来自@akrun 第一个解决方案:
library(tidyverse)
alllist %>% map(~ bind_rows(.x) %>% unname %>% t)
#> [[1]]
#> [,1] [,2] [,3]
#> [1,] 1 2 3
#> [2,] 4 5 6
#>
#> [[2]]
#> [,1] [,2]
#> [1,] 2 4
#> [2,] 5 6
Loop over the list
and rbind
循环
list
并rbind
lapply(alllist, \(x) do.call(rbind, unname(x)))
-output -输出
[[1]]
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[[2]]
[,1] [,2]
[1,] 2 4
[2,] 5 6
Or may use simplify2array
或者可以使用
simplify2array
lapply(alllist, simplify2array)
Do you want an two-dimensional structure/array or simply concatenate the values from the a and b lists?你想要一个二维结构/数组还是简单地连接 a 和 b 列表中的值? If the latter:
如果是后者:
lapply(alllist, function(x) unname(unlist(x)))
[[1]]
[1] 1 2 3 4 5 6
[[2]]
[1] 2 4 5 6
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.