19.1 Introduction

Now that you understand the tree structure of R code, it’s time to return to one of the fundamental ideas that make expr() and ast() work: quotation. In tidy evaluation, all quoting functions are actually quasiquoting functions because they also support unquoting. Where quotation is the act of capturing an unevaluated expression, unquotation is the ability to selectively evaluate parts of an otherwise quoted expression. Together, this is called quasiquotation. Quasiquotation makes it easy to create functions that combine code written by the function’s author with code written by the function’s user. This helps to solve a wide variety of challenging problems.

Quasiquotation is one of the three pillars of tidy evaluation. You’ll learn about the other two (quosures and the data mask) in Chapter 20. When used alone, quasiquotation is most useful for programming, particularly for generating code. But when it’s combined with the other techniques, tidy evaluation becomes a powerful tool for data analysis.

Outline

  • Section 19.2 motivates the development of quasiquotation with a function, cement(), that works like paste() but automatically quotes its arguments so that you don’t have to.

  • Section 19.3 gives you the tools to quote expressions, whether they come from you or the user, or whether you use rlang or base R tools.

  • Section 19.4 introduces the biggest difference between rlang quoting functions and base quoting function: unquoting with !! and !!!.

  • Section 19.5 discusses the three main non-quoting techniques that base R functions uses to disable quoting behaviour.

  • Section 19.6 explores another place that you can use !!!, functions that take .... It also introduces the special := operator, which allows you to dynamically change argument names.

  • Section 19.7 shows a few practical uses of quoting to solve problems that naturally require some code generation.

  • Section 19.8 finishes up with a little history of quasiquotation for those who are interested.

Prerequisites

Make sure you’ve read the metaprogramming overview in Chapter 17 to get a broad overview of the motivation and the basic vocabulary, and that you’re familiar with the tree structure of expressions as described in Section 18.3.

Code-wise, we’ll mostly be using the tools from rlang, but at the end of the chapter you’ll also see some powerful applications in conjunction with purrr.

library(rlang)
library(purrr)

References

Lumley, Thomas. 2001. “Programmer’s Niche: Macros in R.” R News 1 (3): 11–13. https://www.r-project.org/doc/Rnews/Rnews_2001-3.pdf.