Search code examples
rdata-manipulationdata-cleaning

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

Solution

  • 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)