% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/topic-nse.R
\name{topic-defuse}
\alias{topic-defuse}
\alias{quotation}
\alias{nse-defuse}
\title{Defusing R expressions}
\description{
When a piece of R code is defused, R doesn't return its value like it normally would. Instead it returns the expression in a special tree-like object that describes how to compute a value. These defused expressions can be thought of as blueprints or recipes for computing values.

Using \code{\link[=expr]{expr()}} we can observe the difference between computing an expression and defusing it:

\if{html}{\out{<div class="sourceCode r">}}\preformatted{# Return the result of `1 + 1`
1 + 1
#> [1] 2

# Return the expression `1 + 1`
expr(1 + 1)
#> 1 + 1
}\if{html}{\out{</div>}}

Evaluation of a defused expression can be resumed at any time with \code{\link[=eval]{eval()}} (see also \code{\link[=eval_tidy]{eval_tidy()}}).

\if{html}{\out{<div class="sourceCode r">}}\preformatted{# Return the expression `1 + 1`
e <- expr(1 + 1)

# Return the result of `1 + 1`
eval(e)
#> [1] 2
}\if{html}{\out{</div>}}

The most common use case for defusing expressions is to resume its evaluation in a \link[=topic-data-mask]{data mask}. This makes it possible for the expression to refer to columns of a data frame as if they were regular objects.

\if{html}{\out{<div class="sourceCode r">}}\preformatted{e <- expr(mean(cyl))
eval(e, mtcars)
#> [1] 6.1875
}\if{html}{\out{</div>}}
}
\section{Do I need to know about defused expressions?}{
As a tidyverse user you will rarely need to defuse expressions manually with \code{expr()}, and even more rarely need to resume evaluation with \code{\link[=eval]{eval()}} or \code{\link[=eval_tidy]{eval_tidy()}}. Instead, you call \link[=topic-data-mask]{data-masking} functions which take care of defusing your arguments and resuming them in the context of a data mask.

\if{html}{\out{<div class="sourceCode r">}}\preformatted{mtcars \%>\% dplyr::summarise(
  mean(cyl)  # This is defused and data-masked
)
#> # A tibble: 1 x 1
#>   `mean(cyl)`
#>         <dbl>
#> 1        6.19
}\if{html}{\out{</div>}}

It is important to know that a function defuses its arguments because it requires slightly different methods when called from a function. The main thing is that arguments must be transported with the \link[=embrace-operator]{embrace operator} \verb{\{\{}. It allows the data-masking function to defuse the correct expression.

\if{html}{\out{<div class="sourceCode r">}}\preformatted{my_mean <- function(data, var) \{
  dplyr::summarise(data, mean = mean(\{\{ var \}\}))
\}
}\if{html}{\out{</div>}}

Read more about this in:
\itemize{
\item \ifelse{html}{\link[=topic-data-mask]{What is data-masking and why do I need \{\{?}}{\link[=topic-data-mask]{What is data-masking and why do I need curly-curly?}}
\item \ifelse{html}{\link[=topic-data-mask-programming]{Data mask programming patterns}}{\link[=topic-data-mask-programming]{Data mask programming patterns}}
}
}

\section{The booby trap analogy}{
The term "defusing" comes from an analogy to the evaluation model in R. As you may know, R uses lazy evaluation, which means that arguments are only evaluated when they are needed for a computation. Let's take two functions, \code{ignore()} which doesn't do anything with its argument, and \code{force()} which returns it:

\if{html}{\out{<div class="sourceCode r">}}\preformatted{ignore <- function(arg) NULL
force <- function(arg) arg

ignore(warning("boom"))
#> NULL

force(warning("boom"))
#> Warning in force(warning("boom")): boom
}\if{html}{\out{</div>}}

A warning is only emitted when the function actually \emph{triggers} evaluation of its argument. Evaluation of arguments can be chained by passing them to other functions. If one of the functions ignores its argument, it breaks the chain of evaluation.

\if{html}{\out{<div class="sourceCode r">}}\preformatted{f <- function(x) g(x)
g <- function(y) h(y)
h <- function(z) ignore(z)

f(warning("boom"))
#> NULL
}\if{html}{\out{</div>}}

In a way, arguments are like \emph{booby traps} which explode (evaluate) when touched. Defusing an argument can be seen as defusing the booby trap.

\if{html}{\out{<div class="sourceCode r">}}\preformatted{expr(force(warning("boom")))
#> force(warning("boom"))
}\if{html}{\out{</div>}}
}

\section{Types of defused expressions}{
\itemize{
\item \strong{Calls}, like \code{f(1, 2, 3)} or \code{1 + 1} represent the action of calling a function to compute a new value, such as a vector.
\item \strong{Symbols}, like \code{x} or \code{df}, represent named objects. When the object pointed to by the symbol was defined in a function or in the global environment, we call it an environment-variable. When the object is a column in a data frame, we call it a data-variable.
\item \strong{Constants}, like \code{1} or \code{NULL}.
}

You can create new call or symbol objects by using the defusing function \code{expr()}:

\if{html}{\out{<div class="sourceCode r">}}\preformatted{# Create a symbol representing objects called `foo`
expr(foo)
#> foo

# Create a call representing the computation of the mean of `foo`
expr(mean(foo, na.rm = TRUE))
#> mean(foo, na.rm = TRUE)

# Return a constant
expr(1)
#> [1] 1

expr(NULL)
#> NULL
}\if{html}{\out{</div>}}

Defusing is not the only way to create defused expressions. You can also assemble them from data:

\if{html}{\out{<div class="sourceCode r">}}\preformatted{# Assemble a symbol from a string
var <- "foo"
sym(var)

# Assemble a call from strings, symbols, and constants
call("mean", sym(var), na.rm = TRUE)
}\if{html}{\out{</div>}}
}

\section{Local expressions versus function arguments}{
There are two main ways to defuse expressions, to which correspond two functions in rlang, \code{\link[=expr]{expr()}} and \code{\link[=enquo]{enquo()}}:
\itemize{
\item You can defuse your \emph{own} R expressions with \code{expr()}.
\item You can defuse the expressions supplied by \emph{the user} of your function with the \code{en}-prefixed operators, such as \code{enquo()} and \code{enquos()}. These operators defuse function arguments.
}
}

\section{Defuse and inject}{
One purpose for defusing evaluation of an expression is to interface with \link[=topic-data-mask]{data-masking} functions by injecting the expression back into another function with \verb{!!}. This is the \link[=topic-metaprogramming]{defuse-and-inject pattern}.

\if{html}{\out{<div class="sourceCode r">}}\preformatted{my_summarise <- function(data, arg) \{
  # Defuse the user expression in `arg`
  arg <- enquo(arg)

  # Inject the expression contained in `arg`
  # inside a `summarise()` argument
  data |> dplyr::summarise(mean = mean(!!arg, na.rm = TRUE))
\}
}\if{html}{\out{</div>}}

Defuse-and-inject is usually performed in a single step with the embrace operator \ifelse{html}{\code{\link[=embrace-operator]{\{\{}}}{\verb{\{\{}}.

\if{html}{\out{<div class="sourceCode r">}}\preformatted{my_summarise <- function(data, arg) \{
  # Defuse and inject in a single step with the embracing operator
  data |> dplyr::summarise(mean = mean(\{\{ arg \}\}, na.rm = TRUE))
\}
}\if{html}{\out{</div>}}

Using \code{enquo()} and \verb{!!} separately is useful in more complex cases where you need access to the defused expression instead of just passing it on.
}

\section{Defused arguments and quosures}{
If you inspect the return values of \code{expr()} and \code{enquo()}, you'll notice that the latter doesn't return a raw expression like the former. Instead it returns a \link{quosure}, a wrapper containing an expression and an environment.

\if{html}{\out{<div class="sourceCode r">}}\preformatted{expr(1 + 1)
#> 1 + 1

my_function <- function(arg) enquo(arg)
my_function(1 + 1)
#> <quosure>
#> expr: ^1 + 1
#> env:  global
}\if{html}{\out{</div>}}

R needs information about the environment to properly evaluate argument expressions because they come from a different context than the current function. For instance when a function in your package calls \code{dplyr::mutate()}, the quosure environment indicates where all the private functions of your package are defined.

Read more about the role of quosures in \ifelse{html}{\link[=topic-quosure]{What are quosures and when are they needed?}}{\link[=topic-quosure]{What are quosures and when are they needed?}}.
}

\section{Comparison with base R}{
Defusing is known as \emph{quoting} in other frameworks.
\itemize{
\item The equivalent of \code{expr()} is \code{\link[base:bquote]{base::bquote()}}.
\item The equivalent of \code{enquo()} is \code{\link[base:substitute]{base::substitute()}}. The latter returns a naked expression instead of a quosure.
\item There is no equivalent for \code{enquos(...)} but you can defuse dots as a list of naked expressions with \code{eval(substitute(alist(...)))}.
}
}

\keyword{internal}
