Following @Osssan's comments, and assuming that you want to merge everything in your global workspace,
Get the names of the objects and then retrieve the objects themselves into a list:
DF_obj <- lapply(ls(), get)
If you want to merge on all common variables (e.g. if all variable names are unique except the one(s) you want to merge on), then just
Reduce(merge, DF_obj)
should work.
Unfortunately (unlike lapply()
etc.) Reduce
doesn't have a ...
argument for passing additional named arguments to a function, so Reduce(merge, DF_obj, by=common_variable)
doesn't work; as @Osssan points out you need something like
mergefun <- function(x, y) merge(x, y, by= "common_variable")
merged_DF <- Reduce(mergefun, DF_obj )
As other commenters point out, if you just kept the data frames in a list in the first place, you could dispense with the ls()
/get()
step, which is typically clunky/fragile (what if you want to pass the objects back from a function? what if you only want to merge some of the objects in the workspace? ...)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…