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
You can list the bindings in the environment's frame with ls() and see its parent with parent. env() . Another useful way to view an environment is ls. str() .
At the end of a session the objects in the global environment are usually kept in a single binary file in the working directory called . RData. When a new R session begins with this as the initial working directory, the objects are loaded back into memory.
The environment is a virtual space that is triggered when an interpreter of a programming language is launched. Simply, the environment is a collection of all the objects, variables, and functions. Or, Environment can be assumed as a top-level object that contains the set of names/variables associated with some values.
You can set an environment name using attr
, like so:
e <- new.env()
attr(e, "name") <- "xyzzy"
environmentName(e)
## [1] "xyzzy"
If I recall correctly, environment names for packages and namespaces are assigned at the C level. So user-created environments do not reveal names. You cannot set an environment name in R even though there is a (misleadingly named) base function called environmentName()
. It will only return the name assigned at C level. It is really only meant for packages and namespaces, not other environments.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With