Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which function will identify the name of an R variable's enclosing environment?

Tags:

r

I've been reading about R environments, and I'm trying to test my understanding with a simple example:

> f <- function() {
+   x <- 1
+   environment(x)
+ }
> 
> f()
NULL

I'm assuming this means that the object x is enclosed by the environment named NULL, but when I try to list all the objects in that environment, R displays an error message:

> ls(NULL)
Error in as.environment(pos) : using 'as.environment(NULL)' is defunct

So I'm wondering if there's a built-in function I can use on the command line that will return the environment name given the object name. I tried this:

> environment(x)
Error in environment(x) : object 'x' not found

but that returned an error as well. Any help will be greatly appreciated.

like image 775
Robert Avatar asked Jun 15 '15 21:06

Robert


1 Answers

Variables created in function calls are destroyed when the function finishes executing (unless you specifically create them in other persistent environments). As @joran pointed out, when a function is called, a temporary environment is created where local variables are defined, and is destroyed when the function is done executing (that memory is freed). However, as @MrFlick pointed out, if the function returns a function, the returned function maintains a reference to the environment it was created in. You can read more about 'scope', 'stack', and 'heap'. In R there are various ways you can define your variables into specified environments.

f <- function()  {
    x <<- 1  # create x in the global environment (or change it if it's there)
    ## or `assign` x to a value
    ## assign(x, value=1, envir=.GlobalEnv)
}
environment(f)  # where was f defined?
exists("x", envir=.GlobalEnv)
# [1] TRUE
like image 171
Rorschach Avatar answered Sep 27 '22 15:09

Rorschach