as_environment() coerces named vectors (including lists) to an
environment. The names must be unique. If supplied an unnamed
string, it returns the corresponding package environment (see
pkg_env()).
as_environment(x, parent = NULL)
| x | An object to coerce. |
|---|---|
| parent | A parent environment, |
If x is an environment and parent is not NULL, the
environment is duplicated before being set a new parent. The return
value is therefore a different environment than x.
as_env() was soft-deprecated and renamed to as_environment() in
rlang 0.2.0. This is for consistency as type predicates should not
be abbreviated.
# Coerce a named vector to an environment: env <- as_environment(mtcars) # By default it gets the empty environment as parent: identical(env_parent(env), empty_env())#> [1] TRUE# With strings it is a handy shortcut for pkg_env(): as_environment("base")#> <environment: base>as_environment("rlang")#> <environment: package:rlang> #> attr(,"name") #> [1] "package:rlang" #> attr(,"path") #> [1] "/data/GHE/mpn/deployment/deployments/2021-03-05/renv/library/R-3.6/x86_64-pc-linux-gnu/rlang"# With NULL it returns the empty environment: as_environment(NULL)#> <environment: R_EmptyEnv>