dataframe - How can you combine two data frames in r so that the resulting data frame has a new column indicating the data frame of origin? -
suppose have 2 data frames, df1, , df2 , contain same column headers that,
df1 = price size 10 40
and
df2 = price size 20 50
i combine these 2 data frames resulting data frame has, price size origin
10 40 df1 20 50 df2
thoughts?
the easiest way see it, (if have many data sets called df
+ number- though can choose other regex pattern too) them global environment , use do.call/rbind
combination
res <- do.call(rbind, mget(ls(pattern = "^df\\d+$"))) res # price size # df1 10 40 # df2 20 50
if prefer origin column instead of row names, do
res$origin <- row.names(res)
Comments
Post a Comment