combining dataframes using rbind + adding a separate column that includes the names of the individual dataframes [duplicate]

£可爱£侵袭症+ 提交于 2020-12-15 04:19:15

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!