Coerce quoted expressions to quoted formula.

Creates a formula from an expression and an environment. This function is a helper for tools that work with captured expressions. It makes your tools callable with either an expression or a formula, and with an optional environment. When not supplied, the calling environment of the function that called as_fquote() is taken as default.

as_fquote(expr, env = NULL)
A quoted expression or a formula.
The environment of the returned formula. If expr is a formula and if env is supplied, the formula environment is changed to env. If expr is a quoted expression and env is not supplied, the environment is taken from the frame of the function that called the function that called as_fquote() (the grand-parent frame).

as_fquote() makes it straightforward to take an optional environment to associate with a quoted expression. An alternative would be to specify a default environment at each step, e.g. env = caller_env(). In that case however, there is no easy way of communicating the optional nature of env. This is necessary to avoid overriding the environment of formulas supplied as expr with the optional default.

  • as_fquote
# as_fquote() is meant to be called at every step of the way, so
# that each function can figure out a good default for `env`:
api_function <- function(expr, env = NULL) {
  f <- as_fquote(expr, env)
expr_tool <- function(expr, env = NULL) {
  f <- as_fquote(expr, env)
  # *** Do something useful with f ***

# Then the user can supply an expression or a formula. If an
# expression, and no environment is supplied, the caller
# environment is taken as default:
f <- api_function(quote(foobar))

# The user can supply her own environment:
env <- new_env()
f <- api_function(quote(foobar), env)
identical(env(f), env)

# With a formula, the default is to take the formula environment
# rather than the caller environment:
my_f <- env_set(~expr, env)
f <- api_function(my_f)
identical(env(f), env)

# But the user can choose to provide her own environment as well:
f <- api_function(my_f, base_env())
identical(env(f), base_env())
Documentation reproduced from package rlang, version, License: GPL-3

Community examples

Looks like there are no examples yet.