R:如何合并/合并两个环境? [英] R: how do you merge/combine two environments?
问题描述
这是一个简单的问题,但答案显然不是那么简单...是否可以在R中组合环境?
This is a simple question but the answer is apparently not so simple... Is it possible to combine environments in R?
E1 = new.env()
E2 = new.env()
E1$x = 25
E2$y = 7
好,现在我想要一个同时定义了 x
和 y
的环境(例如 E3
).
Ok, now I want an environment (say, E3
) that has both x
and y
defined.
c(E1, E2)
#doesn't work
E3 = new.env(E1, E2)
#doesn't work
我发现了其他类似的问题,但它们没有似乎为我工作.
I have found other similar questions but they don't seem to work for me.
用例:也许有一个不容易的原因……我要这样做的原因是:我使用一些函数来加载数据.以前,我只是将其加载到全局环境中,但是现在我有许多不同的函数来加载不同类型的数据(根据需要可以对其进行不同的调用),因此我希望对加载的数据进行更多的划分.如果我调用2个不同的加载函数 E1 = loadData1()
和 E2 = loadData2()
,现在我要调用一个使用这两个函数中的变量的函数,我想说 with(E1& E2,someFunction())
.因此,合并加载的环境似乎是合适的.
Use case: Maybe there's a reason this isn't easy...the reason I want to do this is thus: I use some functions to load up data. Previously, I've just loaded it into the global environment, but I now have many different functions loading different types of data (which I call variously as needed), and so I wanted to keep the loaded data a bit more compartmentalized. If I call 2 different loading functions E1=loadData1()
and E2=loadData2()
, and I now want to call a function that uses variables from both of these functions, I'd like to be able to say with(E1 & E2, someFunction())
. Hence, merging my loaded environments seems appropriate.
那么,合并它们的正确方法是什么?而且,顺便说一句,如果合并环境不是正确的方法,您是否对如何更好地完成我的工作有不同的建议?
So, what's the right way to merge them? And, as an aside, do you have a different suggestion for how to better accomplish what I'm doing, if merging environments is not the right way?
推荐答案
1)使一个环境成为另一个环境的父项,并使用 with(child,...)
:
1) Make one environment the parent of the other and use with(child, ...)
:
parent <- new.env(); parent$x <- 1
child <- new.env(parent = parent); child$y <- 2
with(child, x + y) # x comes from child and y from parent
## [1] 3
您可以根据需要在尽可能长的链中链接任意数量的环境.
You can link as many environments as you like in as long a chain as necessary.
请注意,如果最初创建的孩子没有父母,那么以后可以使用以下方法添加父母:
Note that if the child were initially created with no parent then you can add a parent later using:
parent.env(child) <- parent
因此我们将 LoadData1
和 LoadData2
定义为:
# define LoadData1 to have a parent argument
LoadData1 <- function(parent = emptyenv()) {
# calculation of environment e goes here
parent.env(e) <- parent
e
}
# define LoadData2 to have a parent argument
LoadData2 <- function(parent = emptyenv()) {
# calculation of environment e goes here
parent.env(e) <- parent
e
}
# run
e1 <- LoadData1()
e2 <- LoadData2(parent = e1)
with(e2, dataFrom1 + dataFrom2)
如果您不想从现在的状态修改 LoadData1
和 LoadData2
:
If you don't want to modify LoadData1
and LoadData2
from what they are now:
e1 <- LoadData1()
e2 <- LoadData2()
parent.env(e2) <- e1
with(e2, dataFrom1 + dataFrom2)
2)转换为列表:
with(c(as.list(e1), as.list(e2)), somefunction())
添加第二种方法.
这篇关于R:如何合并/合并两个环境?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!