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

血红的双手。 提交于 2021-02-05 06:44:06

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/36725013/how-do-i-merge-all-data-frames-in-the-global-environment

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!