如何合并全局环境中的所有数据框? [英] How do I merge all data frames in the global environment?

查看:32
本文介绍了如何合并全局环境中的所有数据框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在全局环境中有几十个数据框.我想在不输入所有名称的情况下合并所有这些.

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.

我该怎么做?

推荐答案

按照@Osssan 的评论,假设您想合并全局工作区中的所有内容

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)

应该可以.

不幸的是(与 lapply() 等不同)Reduce 没有 ... 参数来将额外的命名参数传递给函数,所以 Reduce(merge, DF_obj, by=common_variable) 不起作用;正如@Osssan 指出的那样,您需要类似

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 )

正如其他评论者指出的那样,如果您首先将数据框保存在列表中,则可以省去 ls()/get()步骤,这通常是笨重/脆弱的(如果您想从函数中传回对象怎么办?如果您只想合并工作区中的某些对象怎么办?...)

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

这篇关于如何合并全局环境中的所有数据框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆