0

Just a question on rbind.

When running df_all <- rbind(df_1, df_2 ...) to combine multiple dataframes, I was wondering whether is it possible to add in a separate column that includes the names of the individual dataframes where each observation originates from?

Many Thanks, Mervyn

MervS
  • 3
  • 3
  • `dplyr::bind_rows(df_1, df_2, .., .id = 'id')` ? – Ronak Shah Sep 03 '20 at 01:16
  • Hey Ronak, thanks for your answer! I tried this out, and while it does generate a separate column, it does not contain the names of the dataframe that each observation belongs to – MervS Sep 03 '20 at 01:23

1 Answers1

0

Try this approach :

library(dplyr)
new_df <- bind_rows(lst(df_1, df_2), .id = 'id')

Similarly, if there are lot of such dataframes you don't need to write them one by one. Create a string vector using paste0 and then use mget + bind_rows.

new_df <- bind_rows(mget(paste0('df_', 1:2)), .id = 'id')

You can change 2 to whatever number of dataframes that you have in your global environment.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213