Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have dozens of data frames in the global environment. I want to merge all of them without typing the names of all of them.

How do I do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
766 views
Welcome To Ask or Share your Answers For Others

1 Answer

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? ...)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...