3 Do you need tidy eval?

In computer science, frameworks like tidy evaluation are known as metaprogramming. Modifying the blueprints of computations amounts to programming the program, i.e. metaprogramming. In other languages, this type of approach is often seen as a last resort because it requires new skills and might make your code harder to read. Things are different in R because of the importance of data masking functions, but it is still good advice to consider other options before turning to tidy evaluation. In this section, we review several strategies for solving programming problems with tidyverse packages.

Before diving into tidy eval, make sure to know about the fundamentals of programming with the tidyverse. These are likely to have a better return on investment of time and will also be useful to solve problems outside the tidyverse.

  • Fixed column names. A solid function taking data frames with fixed column names is better than a brittle function that uses tidy eval.

  • Automating loops. dplyr excels at automating loops. Acquiring a good command of rowwise vectorisation and columnwise mapping may prove very useful.

Tidy evaluation is not all-or-nothing, it encompasses a wide range of features and techniques. Here are a few techniques that are easy to pick up in your workflow:

  • Passing expressions through {{ and ....
  • Passing column names to .data[[ and one_of().

All these techniques make it possible to reuse existing components of tidyverse grammars and compose them into new functions.

3.1 Fixed column names

A simple solution is to write functions that expect data frames containing specific column names. If the computation always operates on the same columns and nothing varies, you don’t need any tidy eval. On the other hand, your users must ensure the existence of these columns as part of their data cleaning process. This is why this technique primarily makes sense when you’re writing functions tailored to your own data analysis uses, or perhaps in functions that interface with a specific web API for retrieving data. In general, fixed column names are task specific.

Say we have a simple pipeline that computes the body mass index for each observation in a tibble:

We could extract this code in a function that takes data frames with columns mass and height:

It’s always a good idea to check the inputs of your functions and fail early with an informative error message when their assumptions are not met. In this case, we should validate the data frame and throw an error when it does not contain the expected columns:

In fact, we could go even further and validate the contents of the columns in addition to their names:

Spending your programming time on the domain logic of your function, such as input and scale validation, may have a greater payoff than learning tidy eval just to improve its syntax. It makes your function more robust to faulty data and reduces the risks of erroneous analyses.

3.2 Automating loops

Most programming problems involve iteration because data transformations are typically achieved element by element, by applying the same recipe over and over again. There are two main ways of automating iteration in R, vectorisation and mapping. Learning how to juggle with the different ways of expressing loops is not only an important step towards acquiring a good command of R and the tidyverse, it will also make you more proficient at solving programming problems.

3.2.1 Vectorisation in dplyr

dplyr is designed to optimise iteration by taking advantage of the vectorisation of many R functions. Rowwise vectorisation is achieved through normal R rules, which dplyr augments with groupwise vectorisation. Rowwise vectorisation

Rowwise vectorisation in dplyr is a consequence of normal R rules for vectorisation. A vectorised function is a function that works the same way with vectors of 1 element as with vectors of n elements. The operation is applied elementwise (often at the machine code level, which makes them very efficient). We have already mentioned the vectorisation of toupper(), and many other functions in R are vectorised. One important class of vectorised functions is the arithmetic operators:

Technically, a function is vectorised when:

  • It returns a vector as long as the input.
  • Applying the function on a single element yields the same result than applying it on the whole vector and then subsetting the element.

In other words, a vectorised function fn fulfills the following identity:

When you mix vectorised and non-vectorised operations, the combined operation is itself vectorised when the last operation to run is vectorised. Here we’ll combine the vectorised / function with the summary function mean(). The result of this operation is a vector that has the same length as the LHS of /:

Note that the other combination of operations is not vectorised because in that case the summary operation has the last word:

The dplyr verb mutate() expects vector semantics. The operations defining new columns typically return vectors as long as their inputs:

In fact, mutate() enforces vectorisation. Returning a smaller vector is an error unless it has size 1. If the result of a mutate expression has size 1, it is automatically recycled to the tibble or group size. This ensures that all columns have the same length and fit within the tibble constraints of rectangular data:

In contrast to mutate(), the dplyr verb summarise() expects summary operations that return a single value: Groupwise vectorisation

Things get interesting with grouped tibbles. dplyr augments the vectorisation of normal R functions with groupwise vectorisation. If your tibble has ngroup groups, the operations are repeated ngroup times.

If the operation is entirely vectorised, the result will be the same whether the tibble is grouped or not, since elementwise computations are not affected by the values of other elements. But as soon as summary operations are involved, the result depends on the grouping structure because the summaries are computed from group sections instead of whole columns.

Whereas rowwise vectorisation automates loops over the elements of a column, groupwise vectorisation automates loops over the levels of a grouping specification. The combination of these is very powerful.

3.2.2 Looping over columns

Rowwise and groupwise vectorisations are means of looping in the direction of rows, applying the same operation to each group and each element. What if you’d like to apply an operation in the direction of columns? This is possible in dplyr by mapping functions over columns.

Mapping functions is part of the functional programming approach. If you’re going to spend some time learning new programming concepts, acquiring functional programming skills is likely to have a higher payoff than learning about the metaprogramming concepts of tidy evaluation. Functional programming is inherent to R as it underlies the apply() family of functions in base R and the map() family from the purrr package. It is a powerful tool to add to your quiver. Mapping functions

Everything that exists in R is an object, including functions. If you type the name of a function without parentheses, you get the function object instead of the result of calling the function:

In its simplest form, functional programming is about passing a function object as argument to another function called a mapper function, that iterates over a vector to apply the function on each element, and returns all results in a new vector. In other words, a mapper functions writes loops so you don’t have to. Here is a manual loop that applies toupper() over all elements of a character vector and returns a new vector:

Using a mapper function results in much leaner code. Here we apply toupper() over all elements of letters and return the results as a character vector, as indicated by the suffix _chr:

In practice, functional programming is all about hiding for loops, which are abstracted away by the mapper functions that automate the iteration.

Mapping is an elegant way of transforming data element by element, but it’s not the only one. For instance, toupper() is actually a vectorised function that already operates on whole vectors element by element. The fastest and leanest code is just:

Mapping functions are more useful with functions that are not vectorised or for computations over lists and data frame columns where the vectorisation occurs within the elements or columns themselves. In the following example, we apply a summarising function over all columns of a data frame: Scoped dplyr variants

dplyr provides variants of the main data manipulation verbs that map functions over a selection of columns. These verbs are known as the scoped variants and are recognizable from their _at, _if and _all suffixes.

Scoped verbs support three sorts of selection:

  1. _all verbs operate on all columns of the data frame. You can summarise all columns of a data frame within groups with summarise_all():

  2. _if verbs operate conditionally, on all columns for which a predicate returns TRUE. If you are familiar with purrr, the idea is similar to the conditional mapper purrr::map_if(). Promoting all character columns of a data frame as grouping variables is as simple as:

  3. _at verbs operate on a selection of columns. You can supply integer vectors of column positions or character vectors of colunm names.

    More interestingly, you can use vars()3 to supply the same sort of expressions you would pass to select()! The selection helpers make it very convenient to craft a selection of columns to map over.

The scoped variants of mutate() and summarise() are the closest analogue to base::lapply() and purrr::map(). Unlike pure list mappers, the scoped verbs fully implement the dplyr semantics, such as groupwise vectorisation or the summary constraints:

The other scoped variants also accept optional functions to map over the selection of columns. For instance, you could group by a selection of variables and transform them on the fly:

or transform the column names of selected variables:

The scoped variants lie at the intersection of purrr and dplyr and combine the rowwise looping mechanisms of dplyr with the columnwise mapping of purrr. This is a powerful combination.

  1. vars() is the function that does the quoting of your expressions, and returns blueprints to its caller. This pattern of letting an external helper quote the arguments is called external quoting.