简体   繁体   中英

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:

[[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:

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

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM