3

I have three datasets (tibble), all with the same column names

A_table <- tibble(col_1 = c(1,2), col_2 = c("a1", "a2"))
B_table <- tibble(col_1 = c(1,4), col_2 = c("b11", "b3"))
C_table <- tibble(col_1 = c(5,9), col_2 = c("c21", "c2"))

tables <- ls(pat = "_table")                  

#doesnt work:
combine <- tables %>% 
  reduce(bind_rows)

The combine doesn't work because tables is just a list with the table names, not with the real tables.

What is an easy way to combine the three tables? How do I get the tables in the variable tables and not only the table names using a pattern?

I don't want to bind them manually, e.g.:

  combine <- A_table %>% 
    bind_rows(B_table) %>% 
    bind_rows(C_table)

because in I have many more columns that I want to combine.

I appreciate any advise! Thank you!

C. Sebastian
  • 123
  • 8

2 Answers2

5

With mget + bind_rows:

bind_rows(mget(tables))

# # A tibble: 6 × 2
#   col_1 col_2
#   <dbl> <chr>
# 1     1 a1   
# 2     2 a2   
# 3     1 b11  
# 4     4 b3   
# 5     5 c21  
# 6     9 c2  
Maël
  • 45,206
  • 3
  • 29
  • 67
2

Another option could be using do.call with rbind and mget like this:

do.call(rbind, mget(tables))
#> # A tibble: 6 × 2
#>   col_1 col_2
#> * <dbl> <chr>
#> 1     1 a1   
#> 2     2 a2   
#> 3     1 b11  
#> 4     4 b3   
#> 5     5 c21  
#> 6     9 c2

Created on 2023-06-05 with reprex v2.0.2

Quinten
  • 35,235
  • 5
  • 20
  • 53