Search code examples
rdataframerbind

R performing r rbind on dataframes some of which are empty


I have a number of dataframes that I want to join together. The problem is that some of these may at times be empty and this produces an error message

eg if df3 is empty

rbind(df1, df2, df3)

gives an error message

Error: object 'df3' not found

How can I make rbind ignore empty dataframes and only bind the ones that exist. Thank you for your help.


Solution

  • We can load the dataset into a list and use bind_rows. The advantage is that only those datasets that are created in the global env gets loaded

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

    Or another option is to create a condition with exists

    do.call(rbind, lapply(paste0("df", 1:3), function(x)
              if(exists(x, .GlobalEnv)) get(x) else NULL))