问题
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
回答1:
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.
来源:https://stackoverflow.com/questions/63715456/combining-dataframes-using-rbind-adding-a-separate-column-that-includes-the-na