Creating and Inspecting Environments
Use new.env(), environment(), ls(), and get() to work with environments.
Creating a New Environment
new.env(parent = e) creates a new empty environment. The parent argument sets which environment is searched when a name is not found in the new one. Use emptyenv() for a fully isolated environment.
# Isolated environment (no parent chain)
e1 <- new.env(parent = emptyenv())
# Environment with global as parent
e2 <- new.env(parent = globalenv())
cat('e1 parent:', environmentName(parent.env(e1)), '\n')
cat('e2 parent:', environmentName(parent.env(e2)), '\n')assign() — Add Bindings
assign('name', value, envir = e) creates or updates a named binding in the specified environment. It is the programmatic equivalent of e$name <- value, but works when the name is stored in a variable.
e <- new.env(parent = emptyenv())
assign('x', 10, envir = e)
assign('y', 'hello', envir = e)
assign('z', TRUE, envir = e)
cat('x:', get('x', envir = e), '\n')
cat('y:', get('y', envir = e), '\n')All lessons in this course
- What Is an Environment in R?
- Lexical Scoping Rules
- Global vs Local Scope
- Creating and Inspecting Environments