bind_rows with a large number of tibbles

Viewed 86

I have a large number of tibbles that I'd like to combine into a single tibble using the bind_rows command from dplyr. All tibbles have the same column headers. I want to avoid having to type out the names of all the tibbles in the command. There is an obvious pattern to the naming convention of these tibbles. Here's the long-hand version:

all <- distinct(bind_rows(
          level1_1, level1_2, level1_3, level1_4, level1_5, level1_6, level1_7, level1_8,
          level2_2, level2_3, level2_4, level2_5, level2_6, level2_7, level2_8,
          level3_3, level3_4, level3_5, level3_6, level3_7, level3_8,
          level4_4, level4_5, level4_6, level4_7, level4_8,
          level5_5, level5_6, level5_7, level5_8,
          level6_6, level6_7, level6_8,
          level7_7, level7_8,
          level8_8))

I wonder if there's a more compact way of writing this command?

1 Answers

We can get the values of objects into a list with mget from the string object names returned with ls by specifying the pattern

library(dplyr)
out <- distinct(bind_rows(mget(ls(pattern = '^level\\d+_\\d+$'))))

The pattern suggests to check for objects in the global environment that starts (^) with 'level', followed by one or more digits (\\d+), then an underscore and one or more digits (_\\d+) till the end ($) of the string


If there are other objects of similar pattern and want to constrain it with specific object names, create the combinations with expand.grid and paste

nm1 <- with(subset(expand.grid(1:8, 1:8), Var1 >= Var2), 
        paste0("level", Var2, "_", Var1))
distinct(bind_rows(mget(nm1)))
Related