0
votes

I would like to rbind multiple data frames together. These data frames are data from SQL. At times some of the dataframes might be empty.

Code:

combined = rbind(df1,df2,df3,df4)

If one of the dataframes is empty, it returns a compile error. How do I rbind even if it is empty? Or is there a better way to handle this?

3
do.call(rbind, list(df1, df2, df3, df4))? - jay.sf
In base R, @jay.sf's suggestion is certainly the best. I find I prefer (depending on the library set I'm using) dplyr::bind_rows or data.table::rbindlist (slight code-golf, not sure if there's much more than that for me). - r2evans

3 Answers

4
votes

You could use do.call and coerce you dataframes into a list

do.call(rbind, list(df1, df2, df3, df4))
1
votes

data.table offers a rbindlist function that works similarly (but is more efficient) than do.call-rbind combo

library(data.table)
rbindlist(lapply(setDT, list(df1,df2,df3,df4)))

You can add use.names = TRUE and fill = TRUE if your columns are not in the same order in all columns.

0
votes

We can use bind_rows

library(dplyr)
bind_rows(mget(ls(pattern = '^df\\d+$'))