Home > Blockchain >  Row bind tibbles with the same name within a list of several lists
Row bind tibbles with the same name within a list of several lists

Time:09-16

I have a list containing several lists each containing 4 tibbles named "A", "B", "C", "D":

list_1[["A"]], list_1[["B"]], list_1[["C"]], list_1[["D"]]
list_2[["A"]], list_2[["B"]], list_2[["C"]], list_2[["D"]]
list_3[["A"]], list_3[["B"]], list_3[["C"]], list_3[["D"]] etc.

all_lists <- list(list_1, list_2, list_3, .etc.)

All of those tibbes have the same amount of columns and I would like to row bind all [["A"]] tibbles, all [["B"]] tibbles of the lists and so on.

I'm pretty sure this is something for the map() function family of purrr but have no clue how to tell map() to only use rbind() on specific tibbles within those lists (i.e. tibbles with the same name). Or is this something for the reduce() function?

I would be thankful for any advice!

CodePudding user response:

I got it working with

all_lists <- map_depth(all_lists, 2, ~.x %>% mutate(across(everything(), as.character)))

to make sure that rowbind would work and then

new_list <- all_lists %>% 
  pmap(bind_rows)

CodePudding user response:

If the order is always alphabetically similar, you could use map2

library(purrr)
list_1  <- list("A" = mtcars[1,1:5], "B" =  mtcars[1,1:2], "C" = mtcars[1,1:3])
list_2 <- list("A" = mtcars[2,1:5], "B" = mtcars[2:5,1:2], "C"= mtcars[1:10,1:3])

list_comb <- map2(list_1, list_2, rbind)
  • Related