R Environment Lookup
Every environment has a parent environment. A lookup that misses in one environment continues in the parent.
A miss in one environment searches the parent
city lives in the global environment. The inner environment finds it through its parent, and inherits = FALSE blocks that search.
city <- "Seattle"
inner <- new.env()
print(exists("city", envir = inner))
print(exists("city", envir = inner, inherits = FALSE))The search climbs more than one parent
z lives in the global environment. get searches the inner environment first, then its parent, then the global environment.
z <- 5
mid <- new.env()
inner <- new.env(parent = mid)
print(get("z", envir = inner))The parent of a fresh environment
A fresh environment at the top level has the global environment as its parent. The empty environment ends every chain.
e <- new.env()
print(environmentName(parent.env(e)))
print(emptyenv())Example
rate <- 0.2
store <- new.env()
aisle <- new.env(parent = store)
print(get("rate", envir = aisle))
print(exists("rate", envir = aisle, inherits = FALSE))Key points
- parent.env() returns the environment one step above a given environment.
- Lookup walks up the chain of parents until the name is found.
- The chain ends at the empty environment, which holds nothing.
- The global environment sits near the top of the chain.
- exists() and get() search the parents by default, and inherits = FALSE stops the search at the first environment.
In this example rate lives in the global environment. The aisle environment finds it through the store environment above it, and the second check shows the name is not stored in the aisle itself.
Note
only the empty environment is printed in this lesson, because other environments print a memory address.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท rdrr.io R Snippets
Exercise
A name lives only in a parent environment. What does exists return for it with inherits = FALSE?