Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

merging more than 2 data frames whilst assigning an identifier factor in R

Take this very simple RWE, I want to know what package can be used to automatically assign a factor (preferable the data frame name) when we merge two or more data.frames

I have manually defined the factor in the example below and shown the desired output. But i want to automate it as I have over 100 tables to merge. Note that the headers within each df are constant, only the name itself changes

A <- 1:5
B <- 5:1

df1 <- data.frame(A,B)

A <- 2:6
B <- 6:2

df2 <- data.frame(A,B)

df1$ID <- rep("df1", 5)
df2$ID <- rep("df2", 5)

big_df <- rbind(df1,df2)
like image 712
lukeg Avatar asked Feb 03 '26 02:02

lukeg


1 Answers

Assuming that your data.frame names follow a certain pattern like beginning with "df" followed by numbers and they are not inside a list but simply in your global environment, you can use the following:

library(data.table)
bigdf <- rbindlist(Filter(is.data.frame, mget(ls(pattern = "^df\\d+"))), id = "ID")

Without data.table, you could do it as follows:

lst <- Filter(is.data.frame, mget(ls(pattern = "^df\\d+")))
bigdf <- do.call(rbind, Map(function(df, id) transform(df, ID=id), lst, names(lst)))
like image 128
talat Avatar answered Feb 04 '26 16:02

talat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!