1

I have several data.tables with different columns that I would like to append/rowbind. The outcome should be a data.table with all columns (not only columns appearing all of the rbinded dataset). Here is an example

library(data.table)
df1 = data.frame(a = c(1:5), b = c(6:10))
df2 = data.frame(a = c(11:15), b = c(16:20), c = LETTERS[1:5])
rbindlist(list(df1, df2), fill = TRUE)

borrowed from @kdauria's answer in this post Combine two data frames by rows (rbind) when they have different sets of columns.

But I only know my datasets as a vector of names c("a","b") because they vary from occasion to occasion. Because of that I am doing the following

goo <- function(...) rbind(...,fill=TRUE)
do.call(goo,sapply(c("a","b"),function(x) eval(parse(text=x))))

which gets the job done, but I am thinking whether there is not a more clever way construct the do.call() call.

  • 2
    Related: [list data.tables in memory and combine by row (rbind)](https://stackoverflow.com/questions/30373307/list-data-tables-in-memory-and-bind-them); [Combine several data frames in the global environment by row (rbind)](https://stackoverflow.com/questions/22902411/combine-several-data-frames-in-the-global-environment-by-row-rbind) – Henrik Jul 08 '20 at 18:28
  • The "duplicate" does not take into consideration that the data tables have different columns (just to make it clear for potential future users). – Jesper Hybel Pedersen Jul 08 '20 at 19:28

1 Answers1

3

mget():

a = data.frame(a = c(1:5), b = c(6:10))
b = data.frame(a = c(11:15), b = c(16:20), c = LETTERS[1:5])
vn <- c("a","b")

rbindlist(mget(vn), fill = TRUE)

#      a  b    c
#  1:  1  6 <NA>
#  2:  2  7 <NA>
#  3:  3  8 <NA>
#  4:  4  9 <NA>
#  5:  5 10 <NA>
#  6: 11 16    A
#  7: 12 17    B
#  8: 13 18    C
#  9: 14 19    D
# 10: 15 20    E
s_baldur
  • 29,441
  • 4
  • 36
  • 69