14 Tidy evaluation

Now, we’ll go into some more detail about tidy evaluation. We’ll explain when and why you need tidy evaluation, and what’s going on with enquo(), !!, and !!!.

You don’t always need tidy evaluation when programming with dplyr. For example, the following function works just fine.

But if we want to make this function more general by adding an argument to specify a column, we’ll run into trouble.

You need tidy evaluation if you want to build a function that passes the names of tibble columns into dplyr verbs.

Here’s another example of a function that doesn’t work:

In the following sections, we’ll explore why grouped_mean() doesn’t work and show you how to create a function that does.

14.1 Quoting functions

14.1.1 Quoted arguments

Before we can explain what’s going wrong in functions like grouped_mean(), we need to lay some groundwork. In R, you can divide function arguments into two classes: evaluated and quoted.

Evaluated arguments are what you might think of as “normal.” Here’s an example of a function that evaluates its function arguments.

We can also save 2 as a variable and get the same answer.

Code in an evaluated argument executes the same regardless of whether or not it’s in a function argument. So x evaluates to 2 whether it’s outside log()

or inside.

Because log() evaluates its arguments, it figures out what x refers to before operating on x. In our example, log() figures out that x refers to 2, and then takes the log of 2. For a function like log(), evaluating its argument seems like an obviously good idea. It would be meaningless to take the log of the letter “x”. Sometimes, however, functions don’t want to evaluate their arguments. Let’s find out if dplyr functions use evaluated arguments. Here’s a dplyr function.

In this case, let’s just consider the cty argument, even though mpg is technically an argument as well.

If select() evaluates its argument, then cty should evaluate to the same thing inside select() as it does outside select(). Inside select(), we know that cty somehow refers to a column of mpg. Does it evaluate to a column of mpg outside select()?

No. R doesn’t know what cty refers to, because cty, unlike x, doesn’t exist in the global environment. It only exists as an element of mpg.

To make this point even more explicit, let’s assign a number to cty.

Now, cty evaluates to 3 outside select(), but select(cty) still works as expected.

Arguments like cty are quoted. Instead of immediately evaluating cty before operating, select() and the other dplyr verbs hold on to what was literally supplied as an argument. Here, that’s just “cty”, but other cases can be more complicated. Quoting allows select() and the other dplyr verbs to use their input as they want without worrying about how that input evaluates in the global environment. In our example, quoting its argument allows select() to look for cty inside the mpg tibble, without worrying about cty referring to 3 in the global environment.

Note that dplyr verbs only quote the arguments that supply column names. They do not quote the argument that refers to the data you pipe in, or non-column-name arguments like count()’s sort argument or top_n()’s n argument.

dplyr’s quoting behavior makes it really easy to use. You can supply bare names of columns to dplyr functions and they just work. However, the quoting behavior causes some wrinkles when you want to program with dplyr.

You might now have a hypothesis about why grouped_mean() didn’t work. Here it is again.

The error says that the column group_var is unknown. Because group_by() quotes its argument, it didn’t evaluate group_var, find out that it refers to manufacturer, and then look for a column named manufacturer. Instead, it took its input literally and looked for a column named group_var. mpg doesn’t have a column called group_var, so we got an error.

We want group_by() to understand that group_var refers to manufacturer, so we need to change our function. Before diving into these changes, here’s a summary of the points covered so far:

  • Some functions evaluate their arguments and some function quote their arguments.
  • If a function quotes its argument, the argument will evaluate differently inside and outside the function.
  • dplyr functions quote the arguments that take tibble column names.

14.1.2 Strings and glue()

If we want group_by() to understand that group_var refers to manufacturer, we’re going to have to unquote group_var.

Before we talk about how to do this with dplyr, let’s take a moment to examine a situation in which you’ve actually already been quoting and unquoting input.

When you create a string, R doesn’t evaluate its contents. When you type something like:

R creates a string, not an object named y with a value of 1.

Sometimes, though, you’ll want to write a function that inserts a variable into a string. For example, say we want to write a function that tells you what species of animal you are.

You can probably predict that the following function won’t work.

We need to tell our function that we actually do want to evaluate my_species. As you’ve already learned, you can do this with str_glue and {}.

The {} tells str_glue() to evaluate my_species before constructing the string. Unfortunately, we can’t just use {} to get dplyr verbs to evaluate the arguments we want. We’ll need to figure out an equivalent to {} for dplyr function calls.

14.1.3 Quosures

One reason we can’t just generalize from our string example and use {} is that when dplyr functions quote their arguments, they don’t quote and create strings. When you quote with quotation marks, as you know, you create a string.

But when dplyr functions quote their arguments, they create something called a quosure.

You can create your own quosure with the function quo().

Our quosure has two parts: the expr (which stands for expression) and the env (which stands for environment).

You can think of expressions like recipes. A recipe for chocolate chip cookies specifies how to make the cookies, but does not itself create any cookies. Similarly, the expression y <- 1 species how to create a variable, but doesn’t actually create that variable. Just as you need to carry out the recipe to create cookies, R needs to evaluate the expression to produce the results.

Recipes, unfortunately, aren’t sufficient for cookies. You also need a stock of ingredients, like flour and chocolate chips. Similarly, in order to evaluate an expression, R needs an environment that supplies variables. Different types of flour and chocolate chips can create different cookies, and different environments can cause the same expression to be evaluated differently.

If we place quo(y <- 1) inside a function, the environment will change.

Quosures are objects and so can be passed around, carrying their environment with them.

Now you know that:

  • dplyr quotes its arguments and creates quosures, which consist of an expression and an environment. An expression is kind of like a recipe, and the environment is what supplies the ingredients you use to carry out that recipe.
  • You can create a quosure with quo().

14.2 Wrapping quoting functions

14.2.1 enquo() and !!

Now that we’ve gone over some theory, we can return to the task of fixing grouped_mean().

You just learned that dplyr verbs create quosures. In order to make our function work, we’ll need to make our own quosure that captures our desired meaning of group_var and summary_var. Here’s our earlier, unsuccessful function.

We want to track the environment of group_var so that group_by() knows that it refers to manufacturer. We can do this with quo().

Our print() statement lets us know what group_var looks like inside the function. group_var is a quosure and evaluates to manufacturer, which seems like a step in the right direction.

However, our function still isn’t giving us what we want. group_by() still quotes group_var and looks for a column called group_var. We’ve already quoted the input with quo(), but group_by() doesn’t know that and so is just carrying on as usual.

We can tell group_by() not to quote by using !! (pronounced “bang bang”). !! says something like “evaluate me!” or “unquote!”

Success!!

quo() and !! work well, but it’s kind of a hassle to have to quo() our input each time. It would be even better if we could write the function call like this:

To do so, we’ll take care of the quoting inside our function. We can’t use quo() to quote inside our function.

The environment of our quosure is wrong. We want R to evaluate group_var using the global environment, not the environment of our function. We’ll need quo()’s cousin, enquo(), in order to capture the correct environment of group_var.

Now, we can rewrite grouped_mean().

You can use this same technique for any of the dplyr verbs.

The enquo() and !! strategy is incredibly useful, and you don’t need to fully understand the theory behind it in order to write successful functions. If some of the earlier explanation is still confusing, don’t worry about it too much. Tidy evaluation is a complicated subject, and it takes a while to really grasp what’s going on behind enquo() and !!.

In summary, to build a function that takes an argument to a dplyr verb, use the following template:

14.2.2 Passing ...

Say you want to extend grouped_mean() so that you can group by any number of variables. You might have noticed that some functions, like scoped verbs and the purrr functions, take ... as a final argument, allowing you to specify additional arguments. We can use that same functionality here.

Notice that with …, we didn’t have to use enquo() or !!. ... takes care of all the quoting and unquoting for you.

You can also use ... to pass in full expressions to dplyr verbs.

14.3 Passing vectors with !!!

Here’s one more common tidy evaluation use case.

Say you want to use recode() to recode a variable.

It’s often a good idea to store your recode mapping in a parameter because you might want to change the mapping later on or use it in other locations.

We can store the mapping in a named character vector.

However, now recode() doesn’t work.

recode(), like group_by(), summarize(), and the other dplyr functions, quotes its input. We therefore need to tell recode() to evaluate recode_key immediately. Let’s try !!.

!! doesn’t work because recode_key is a vector. Not only do we need to immediately evaluate recode_key, we also need to unpack its contents. To do so, we’ll use !!!.

Success!!!