Reputation: 965
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:
[[1]]
[1] 1 2 3
[1] 4 5 6
[[2]]
[1] 2 4
[1] 5 6
Upvotes: 2
Views: 888
Reputation: 25333
A purrr::map
and dplyr::bind_rows
based approach, which was inspired by @akrun first solution:
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
Upvotes: 3
Reputation: 887251
Loop over the list
and 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
lapply(alllist, simplify2array)
Upvotes: 3
Reputation: 10996
Do you want an two-dimensional structure/array or simply concatenate the values from the a and b lists? If the latter:
lapply(alllist, function(x) unname(unlist(x)))
[[1]]
[1] 1 2 3 4 5 6
[[2]]
[1] 2 4 5 6
Upvotes: 2