I have a list of identically structured lists as follows:
test1 <- list(first = data.frame(col1 = c(1,2), col2 = c(3,4)),
second = data.frame(COL1 = c(100,200), COL2 = c(300, 400)))
test2 <- list(first = data.frame(col1 = c(5,6), col2 = c(7,8)),
second = data.frame(COL1 = c(500,600), COL2 = c(700,800)))
orig.list <- list(test1, test2)
I want to:
- Bind the rows the first element of each nested list together, bind the rows 2nd element of each nested list together, etc.
- Recombine the resulting elements into a single list with an identical structure to the first list.
I can easily do this element by element via:
firsts <- orig.list %>% purr::map(1) %>% dplyr::bind_rows()
seconds <- orig.list %>% purr::map(2) %>% dplyr::bind_rows()
new.list <- list(first = firsts, second = seconds)
However, for n list elements this requires that I:
- know the number of elements in each list,
- know the names and orders of the elements so I can recreate the new list with the correct names and order,
- copy and past the same line of code over and over again.
I'm looking for how to apply purrr:map (or some other tidyverse function) more generically to combine all elements of a list of lists, preserving the element names and order.