How to find waste-free environments?

This is a continuation of the answer to this question to effectively move the environment from the internal function to the global environment , which indicated that it is necessary to return a link to the environment that was created inside the function if you want to work with the contents of this environment

Is it true that the newly created environment continues to exist if we do not return the link, and if so, how does it track such an environment, either to access its contents or to delete it?

+4
source share
1 answer

Of course, if it was assigned to a symbol somewhere outside the function evaluation environment (as it was in the OP example), the environment will continue to exist. In this sense, an environment is similar to any other R. object. (The fact that unassigned environments can be stored in closures means that environments are sometimes saved where other types of objects will not, but that's not what happens here.)

## OP example function
funfun <- function(inc = 1){
    dataEnv <- new.env()
    dataEnv$d1 <- 1 + inc
    dataEnv$d2 <- 2 + inc
    dataEnv$d3 <- 2 + inc
    assign('dataEnv', dataEnv, envir = globalenv())  ## Assignment to .GlobalEnv
}
funfun()
ls(env=.GlobalEnv)
# [1] "dataEnv" "funfun" 

## It easy to find environments assigned to a symbol in another environment,
## if you know which environment to look in.
Filter(isTRUE, eapply(.GlobalEnv, is.environment))
# $dataEnv
# [1] TRUE

In the example, the OP is relatively easy to track because the medium has been assigned to the character in .GlobalEnv. In general, although (and again, like any other R object), it will be difficult to track if, for example, it is assigned an element in the list or a more complex structure.

(, , R . , (, v <- f()), . !)

+4

All Articles