R: Functions -- Display of environment name instead of memory address of that environment?

r

Solution

You could use the recenty released package envnames that I developed precisely as a workaround to this problem.

In your example, if you use the environment_name() function of the package to retrieve the environment of function `f()` you would get `"e1"`, instead of `""` that you get using the built-in function `environmentName()`, that is:

library(envnames)
e1 <- new.env()
e1$z <- 10
f <- function(x) {
   x + z 
}
environment(f) = e1
environment_name(environment(f))

and the output is:

[1] "e1"

In the example given by Hadley where many environments point to the same environment you get ALL those environment names in a named array:

library(envnames)
e1 <- new.env()
e1$z <- 10
e2 <- e1
e3 <- e1

f <- function(x) {
  x + z 
}
environment(f) <- e1
environment_name(environment(f))

where the output includes the location of each environment as the names attribute of the returned array:

R_GlobalEnv R_GlobalEnv R_GlobalEnv 
       "e1"        "e2"        "e3"

Finally, since you mention that seeing the memory address of the environment doesn't tell us much about the user-defined environment we are talking about, you could use the memory address as input argument to the `environment_name()` function to get the name of the environment (or environments) that is associated to the memory address.

The following snippet of code and output illustrates this (where the code was run on your example of one single environment):

> f
function(x) {
       x + z 
    }
<environment: 0x0000000013f15870>
> environment_name("<environment: 0x0000000013f15870>")
[1] "e1"

Problem

What is the way to display the name of the environment inside the function as like built-in functions? For example, when I type the function: mean available in base package, I can see the environment as "namespace:base". ``` mean function (x, ...) UseMethod("mean") <bytecode: 0x0547f17c> **<environment: namespace:base>** ``` However, when I attach a function to the newly created environment, here to access the values for the free variable (z) inside the function (f), it automatically resides in .GlobalEnv environment and the name of the environment is not displayed inside the function, but the memory address "0x051abd60" of (e1) environment is seen. ``` e1 <- new.env() e1$z <- 10 f <- function(x) { x + z } environment(f) = e1 f function(x) { x + z } **<environment: 0x051abd60>** ``` Why do I see this behavior? Why don't I get my environment name inside the function as like built-in functions of R and also the functions available from various R packages? Is there a difference between environment data structure and .GlobalEnv environment available from search() Any pointers towards the motivation behind this behavior would be highly appreciated. Thank you

Original source