更新时间:2022-05-26 22:34:13
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())
添加第二种方法.