[英]R environment issues when creating a package
Let's say I have a function that initializing a new environment:假设我有一个初始化新环境的 function:
init <-function()
{
e <- new.env()
}
Also, the init
function lives in another.R file此外, init
function 存在于 another.R 文件中
Then, after it is initialized, I want to start using it in other function calls in different files like然后,在它初始化之后,我想开始在不同文件中的其他 function 调用中使用它,例如
init.main <- function(e)
{
e$data <- list()
e$number <- 0
}
However, this will throw an error saying object e
is not found.但是,这会抛出一个错误,说 object e
is not found。 I presume this is because e
is only locally initialized, but if I were to use a package that relies solely on function calls, how would I get the functions to be able to talk to each other and use the same environment?我认为这是因为e
仅在本地初始化,但如果我要使用仅依赖 function 调用的 package,我将如何让函数能够相互通信并使用相同的环境?
Here's one method.这是一种方法。
init <- local({
e <- NULL
function() {
e <<- new.env(parent = emptyenv())
}
})
init.main <- function() {
e <- get("e", envir = environment(init))
}
This really depends on whether you want just one e
or you want to be able to have multiple environments with different contents.这实际上取决于您是只想要一个e
还是希望能够拥有具有不同内容的多个环境。
In the first case, simply define e
at the top level in your package, and have your init
function modify that copy.在第一种情况下,只需在 package 的顶层定义e
,并让您的init
function 修改该副本。 For example,例如,
e <- new.env()
init <- function() {
e <<- new.env()
}
Then any other function in your package can see e
and use it.然后您的 package 中的任何其他 function 都可以看到e
并使用它。 Calling init()
will wipe out any previous contents and set it to empty.调用init()
将清除所有以前的内容并将其设置为空。
The other case is a little harder, just because you'll need to handle several functions with the same name that refer to different e
values.另一种情况要困难一些,因为您需要处理几个具有相同名称的函数,这些函数引用不同的e
值。 There's an example of this in section 10.7 of the Introduction to R manual that ships with R. R 附带的 R 简介手册的第 10.7 节中有一个示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.