How can you concatenate two dataframes in r so that a new column appears in the resulting dataframe indicating the origin dataframe?
Suppose I have two dataframes, df1 and df2, and they contain the same column headers, so
df1 =
price size
10 40
and
df2 =
price size
20 50
I would like to combine these two dataframes so that the resulting dataframe, price size origin
10 40 df1
20 50 df2
Thoughts?
+3
Mark
source
to share
2 answers
The easiest way I see is (if you have a lot of datasets named df
+ some number, although you can choose another regex pattern as well) to get them all from the global environment and use the do.call/rbind
combination
res <- do.call(rbind, mget(ls(pattern = "^df\\d+$")))
res
# price size
# df1 10 40
# df2 20 50
If you prefer the source to be a column instead of row names, you could simply do
res$origin <- row.names(res)
+2
David Arenburg
source
to share
You can also do
library(tidyr)
unnest(mget(paste0('df', 1:2)), origin)
# origin price size
#1 df1 10 40
#2 df2 20 50
+1
akrun
source
to share