with_env

0th

Percentile

Evaluate an expression within a given environment.

These functions evaluate expr within a given environment (env for with_env(), or the child of the current environment for locally). They rely on expr_eval() which features a lighter evaluation mechanism than base R eval(), and which also has some subtle implications when evaluting stack sensitive functions (see help for expr_eval()).

Usage
with_env(env, expr)
locally(expr)
Arguments
env
An environment within which to evaluate expr. Can be an object with an env() method.
expr
An expression to evaluate.
Details

locally() is equivalent to the base function local() but it produces a much cleaner evaluation stack, and has stack-consistent semantics. It is thus more suited for experimenting with the R language.

Aliases
  • with_env
  • locally
Examples
# with_env() is handy to create formulas with a given environment:
env <- new_env("rlang")
f <- with_env(env, ~new_formula())
identical(f_env(f), env)

# Or functions with a given enclosure:
fn <- with_env(env, function() NULL)
identical(env(fn), env)


# Unlike eval() it doesn't create duplicates on the evaluation
# stack. You can thus use it e.g. to create non-local returns:
fn <- function() {
  g(env())
  "normal return"
}
g <- function(env) {
  with_env(env, return("early return"))
}
fn()


# Since env is passed to env(), it can be any object with an env()
# method. For strings, the pkg_env() is returned:
with_env("base", ~mtcars)
Documentation reproduced from package rlang, version 0.0.0.9000, License: GPL-3

Community examples

Looks like there are no examples yet.