R environment issues when creating a package

Viewed 42

Let's say I have a function that initializing a new environment:

init <-function()
{
    e <- new.env()
}

Also, the init function lives in another .R file

Then, after it is initialized, I want to start using it in other function calls in different files like

init.main <- function(e)
{
    e$data <- list()
    e$number <- 0
}

However, this will throw an error saying 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?

2 Answers

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.

In the first case, simply define e at the top level in your package, and have your init function modify that copy. For example,

e <- new.env()
init <- function() {
  e <<- new.env()
}

Then any other function in your package can see e and use it. Calling init() will wipe out any previous contents and set it to empty.

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. There's an example of this in section 10.7 of the Introduction to R manual that ships with R.

Related