0

I want to stack all the tables with prefix "vac_" which I have like 2000 of them in total (e.g. vac_0001, vac_0002, vac_0003, ..., vac_2000). I thought that I could use the list, but R treats the list like an element, so is not possible to stack the elements in the list. How can I stack these 2000 tables without having to manually specify all of them?

I have 2000 tables start with "vac_"

listvac <- ls(pattern = "vac_")
listvac
[1] "vac_0001" "vac_0002" "vac_0003" "vac_0004" "vac_0005"

currently I am binding manually

bind_rows(vac_0001, vac_0002, vac_0003, vac_0004, vac_0005)
aprscoder
  • 11
  • 2
  • Related post: https://stackoverflow.com/questions/2851327/convert-a-list-of-data-frames-into-one-data-frame – zx8754 Jul 29 '19 at 13:17

2 Answers2

0

Try:

do.call(rbind, mget(ls(pattern = "vac_")))

Pablo Rod
  • 669
  • 4
  • 10
  • Thanks! I guess this would work too. The only thing is i find bind_rows work well because my tables are not consistent with the columns, as some tables have certain columns but some don't. – aprscoder Jul 29 '19 at 22:14
  • actually i use this suggestion on my other tables where i stack numeric and character within the same column (mainly due to the input of the data which will have to clean up later). It works like magic! Thank you so much!! – aprscoder Jul 30 '19 at 09:12
0

I believe a combination as following:

Getting the variables cf. your pattern:

listvac <- ls(pattern = "vac_")

listvac is not a list, but a vector. I.e. each element in the vector contains a single element, in this case, a string with a name found in the environment. It does not contain the value (contents) of that variable.

Then, retrieve all the tables from all those variables from the current environment and shove them into a list:

all_vac_tables <- mget(listvec)

all_vac_tables should now be a list.

Finally, using dplyr::bind_rows, "stack" 'em. Notice that bind_rows has an argument, .id with which you can name a column that would receive the name of the arguments. Thus,

bind_rows(all_vac_tables, .id='id')
MrGumble
  • 5,631
  • 1
  • 18
  • 33
  • Thanks so much. This works perfectly! I ended up doing this: listvac <- ls(pattern = "vac_") vac_alltables <- bind_rows(mget(listvac)) – aprscoder Jul 29 '19 at 22:08