I am a bit confused by R's lookup mechanism. When I have the following code
# create chain of empty environments
e1 <- new.env()
e2 <- new.env(parent=e1)
e3 <- new.env(parent=e2)
# set key/value pairs
e1[["x"]] <- 1
e2[["x"]] <- 2
then I would expect to get "2" if I look for "x" in environment e3. This works if I do
> get(x="x", envir=e3)
[1] 2
but not if I use
> e3[["x"]]
NULL
Could somebody explain the difference? It seems, that
e3[["x"]]
is not just syntactic sugar for
get(x="x", envir=e3)
Thanks in advance,
Sven
We can use the ls() function to show what variables and functions are defined in the current environment. Moreover, we can use the environment() function to get the current environment.
You can use ls() to list all variables that are created in the environment. Use ls() to display all variables. pat = " " is used for pattern matching such as ^, $, ., etc.
When a function is evaluated, R looks in a series of environments for any variables in scope. The evaluation environment is first, then the function's enclosing environment, which will be the global environment for functions defined in the workspace.
You can open a Command Prompt, type set , and press Enter to display all current environment variables on your PC. You can open PowerShell, type Get-ChildItem Env: , and press Enter to display all current environment variables on your PC.
These functions are different.
get
performs a search for an object in an environemnt, as well as the enclosing frames (by default):
From ?get
:
This function looks to see if the name x has a value bound to it in the specified environment. If inherits is TRUE and a value is not found for x in the specified environment, the enclosing frames of the environment are searched until the name x is encountered. See environment and the ‘R Language Definition’ manual for details about the structure of environments and their enclosures.
In contrast, the [
operator does not search enclosing environments, by default.
From ?'['
:
Both $ and [[ can be applied to environments. Only character indices are allowed and no partial matching is done. The semantics of these operations are those of get(i, env=x, inherits=FALSE)
.
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