Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
724 views
in Technique[技术] by (71.8m points)

r - How do I merge all data frames in the global environment?

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...