generated from r4ds/bookclub-template
-
Notifications
You must be signed in to change notification settings - Fork 25
/
19_Quasiquotation.Rmd
429 lines (308 loc) · 10.8 KB
/
19_Quasiquotation.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
# Quasiquotation
**Learning objectives:**
- What quasiquotation means
- Why it's important
- Learn some practical uses
```{r, message=FALSE}
library(rlang)
library(purrr)
```
## Introduction
Three pillars of *tidy* evaluation
1. Quasiquotation
2. Quosures (chapter 20)
3. Data masks (Chapter 20)
**Quasiquotation = quotation + unquotation**
- **Quote.** Capture unevaluated expression... ("defuse")
- **Unquote.** Evaluate selections of quoted expression! ("inject")
- Functions that use these features are said to use Non-standard evaluation (NSE)
- Note: related to Lisp macros, and also exists in other languages with Lisp heritage, e.g. Julia
> On it's own, Quasiquotation good for programming, but combined with other tools,
> important for data analysis.
## Motivation
Simple *concrete* example:
`cement()` is a function that works like `paste()` but doesn't need need quotes
(Think of automatically adding 'quotes' to the arguments)
```{r}
cement <- function(...) {
args <- ensyms(...)
paste(purrr::map(args, as_string), collapse = " ")
}
cement(Good, morning, Hadley)
```
What if we wanted to use variables? What is an object and what should be quoted?
This is where 'unquoting' comes in!
```{r}
name <- "Bob"
cement(Good, afternoon, !!name) # Bang-bang!
```
## Vocabulary {-}
Can think of `cement()` and `paste()` as being 'mirror-images' of each other.
- `paste()` - define what to quote - **Evaluates** arguments
- `cement()` - define what to unquote - **Quotes** arguments
**Quoting function** similar to, but more precise than, **Non-standard evaluation (NSE)**
- Tidyverse functions - e.g., `dplyr::mutate()`, `tidyr::pivot_longer()`
- Base functions - e.g., `library()`, `subset()`, `with()`
**Quoting function** arguments cannot be evaluated outside of function:
```{r, error = TRUE}
cement(Good, afternoon, Cohort) # No problem
Good # Error!
```
**Non-quoting (standard) function** arguments can be evaluated:
```{r}
paste("Good", "afternoon", "Cohort")
"Good"
```
## Quoting
**Capture expressions without evaluating them**
```{r, echo = FALSE}
data.frame(
t = rep(c("One", "Many"), 3),
Developer = c("`expr()`","`exprs()`",
"`quote()`", "`substitute()`",
"", ""),
User = c("`enexpr()`", "`enexprs()`",
"`alist()`", "`as.list(substitute(...()))`",
"`ensym()`", "`ensyms()`"),
type = c("Expression", "Expression", "R Base", "R Base", "Symbol", "Symbol")) |>
dplyr::group_by(type) |>
gt::gt() |>
gt::tab_row_group(label = "R Base (Quotation)", rows = type == "R Base")|>
gt::tab_row_group(label = "Symbol (Quasiquotation)", rows = type == "Symbol") |>
gt::tab_row_group(label = "Expression (Quasiquotation)", rows = type == "Expression")|>
gt::cols_label(t = "") |>
gt::tab_options(row_group.font.weight = "bold") |>
gt::tab_style(style = gt::cell_text(align = "center", weight = "bold"),
locations = gt::cells_column_labels()) |>
gt::tab_style(style = gt::cell_borders(style = "hidden"), locations = gt::cells_body()) |>
gt::tab_style(style = gt::cell_borders(sides = "top", style = "solid"),
locations = gt::cells_body(rows = c(1, 3, 5))) |>
gt::tab_style(style = gt::cell_borders(sides = "bottom", style = "solid"),
locations = gt::cells_body(rows = c(2, 4))) |>
gt::cols_align("center", columns = -1) |>
gt::fmt_markdown() |>
gt::cols_width(t ~ px(100))
```
- Non-base functions are from **rlang**
- **Developer** - From you, direct, fixed, interactive
- **User** - From the user, indirect, varying, programmatic
Also:
- `bquote()` provides a limited form of quasiquotation
- `~`, the formula, is a quoting function (see [Section 20.3.4](https://adv-r.hadley.nz/evaluation.html#quosure-impl))
### `expr()` and `exprs()` {-}
```{r}
expr(x + y)
exprs(exp1 = x + y, exp2 = x * y)
```
### `enexpr()`^[`enexpr()` = **en**rich `expr()`] and `enexprs()` {-}
```{r}
f <- function(x) enexpr(x)
f(a + b + c)
f2 <- function(x, y) enexprs(exp1 = x, exp2 = y)
f2(x = a + b, y = c + d)
```
### `ensym()` and `ensyms()` {-}
- **[Remember](https://adv-r.hadley.nz/expressions.html#symbols):** Symbol represents the name of an object. Can only be length 1.
- These are stricter than `enexpr/s()`
```{r}
f <- function(x) ensym(x)
f(a)
f2 <- function(x, y) ensyms(sym1 = x, sym2 = y)
f2(x = a, y = "b")
```
## Unquoting
**Selectively evaluate parts of an expression**
- Merges ASTs with template
- 1 argument `!!` (**unquote**, **bang-bang**)
- Unquoting a *function call* evaluates and returns results
- Unquoting a *function (name)* replaces the function (alternatively use `call2()`)
- \>1 arguments `!!!` (**unquote-splice**, **bang-bang-bang**, **triple bang**)
- `!!` and `!!!` only work like this inside quoting function using rlang
### Basic unquoting {-}
**One argument**
```{r}
x <- expr(a + b)
y <- expr(c / d)
```
```{r, collapse = TRUE}
expr(f(x, y)) # No unquoting
expr(f(!!x, !!y)) # Unquoting
```
**Multiple arguments**
```{r}
z <- exprs(a + b, c + d)
w <- exprs(exp1 = a + b, exp2 = c + d)
```
```{r, collapse = TRUE}
expr(f(z)) # No unquoting
expr(f(!!!z)) # Unquoting
expr(f(!!!w)) # Unquoting when named
```
### Special usages or cases {-}
For example, get the AST of an expression
```{r, collapse = TRUE}
lobstr::ast(x)
lobstr::ast(!!x)
```
Unquote *function call*
```{r, collapse = TRUE}
expr(f(!!mean(c(100, 200, 300)), y))
```
Unquote *function*
```{r, collapse = TRUE}
f <- expr(sd)
expr((!!f)(x))
expr((!!f)(!!x + !!y))
```
## Non-quoting
Only `bquote()` provides a limited form of quasiquotation.
The rest of base selectively uses or does not use quoting (rather than unquoting).
Four basic forms of quoting/non-quoting:
1. **Pair of functions** - Quoting and non-quoting
- e.g., `$` (quoting) and `[[` (non-quoting)
2. **Pair of Arguments** - Quoting and non-quoting
- e.g., `rm(...)` (quoting) and `rm(list = c(...))` (non-quoting)
3. **Arg to control quoting**
- e.g., `library(rlang)` (quoting) and `library(pkg, character.only = TRUE)` (where `pkg <- "rlang"`)
4. **Quote if evaluation fails**
- `help(var)` - Quote, show help for var
- `help(var)` (where `var <- "mean"`) - No quote, show help for mean
- `help(var)` (where `var <- 10`) - Quote fails, show help for var
## ... (dot-dot-dot) [When using ... with quoting]
- Sometimes need to supply an *arbitrary* list of expressions or arguments in a function (`...`)
- But need a way to use these when we don't necessarily have the names
- Remember `!!` and `!!!` only work with functions that use rlang
- Can use `list2(...)` to turn `...` into "tidy dots" which *can* be unquoted and spliced
- Require `list2()` if going to be passing or using `!!` or `!!!` in `...`
- `list2()` is a wrapper around `dots_list()` with the most common defaults
**No need for `list2()`**
```{r, collapse = TRUE}
d <- function(...) data.frame(list(...))
d(x = c(1:3), y = c(2, 4, 6))
```
**Require `list2()`**
```{r, collapse = TRUE, error = TRUE}
vars <- list(x = c(1:3), y = c(2, 4, 6))
d(!!!vars)
d2 <- function(...) data.frame(list2(...))
d2(!!!vars)
# Same result but x and y evaluated later
vars_expr <- exprs(x = c(1:3), y = c(2, 4, 6))
d2(!!!vars_expr)
```
Getting argument names (symbols) from variables
```{r}
nm <- "z"
val <- letters[1:4]
d2(x = 1:4, !!nm := val)
```
## `exec()` [Making your own ...] {-}
What if your function doesn't have tidy dots?
Can't use `!!` or `:=` if doesn't support rlang or dynamic dots
```{r, collapse=TRUE, error = TRUE}
my_mean <- function(x, arg_name, arg_val) {
mean(x, !!arg_name := arg_val)
}
my_mean(c(NA, 1:10), arg_name = "na.rm", arg_val = TRUE)
```
Let's use the ... from `exec()`
```{r, eval = FALSE}
exec(.fn, ..., .env = caller_env())
```
```{r, collapse=TRUE}
my_mean <- function(x, arg_name, arg_val) {
exec("mean", x, !!arg_name := arg_val)
}
my_mean(c(NA, 1:10), arg_name = "na.rm", arg_val = TRUE)
```
Note that you do not unquote `arg_val`.
Also `exec` is useful for mapping over a list of functions:
```{r}
x <- c(runif(10), NA)
funs <- c("mean", "median", "sd")
purrr::map_dbl(funs, exec, x, na.rm = TRUE)
```
## Base R `do.call` {-}
`do.call(what, args)`
- `what` is a function to call
- `args` is a list of arguments to pass to the function.
```{r, collapse = TRUE}
nrow(mtcars)
mtcars3 <- do.call("rbind", list(mtcars, mtcars, mtcars))
nrow(mtcars3)
```
### Exercise 19.5.5 #1 {-}
One way to implement `exec` is shown here: Describe how it works. What are the key ideas?
```{r}
exec_ <- function(f, ..., .env = caller_env()){
args <- list2(...)
do.call(f, args, envir = .env)
}
```
## Case Studies (side note)
Sometimes you want to run a bunch of models, without having to copy/paste each one.
BUT, you also want the summary function to show the appropriate model call,
not one with hidden variables (e.g., `lm(y ~ x, data = data)`).
We can achieve this by building expressions and unquoting as needed:
```{r, collapse = TRUE}
library(purrr)
vars <- data.frame(x = c("hp", "hp"),
y = c("mpg", "cyl"))
x_sym <- syms(vars$x)
y_sym <- syms(vars$y)
formulae <- map2(x_sym, y_sym, \(x, y) expr(!!y ~ !!x))
formulae
models <- map(formulae, \(f) expr(lm(!!f, data = mtcars)))
summary(eval(models[[1]]))
```
As a function:
```{r, collapse = TRUE}
lm_df <- function(df, data) {
x_sym <- map(df$x, as.symbol)
y_sym <- map(df$y, as.symbol)
data <- enexpr(data)
formulae <- map2(x_sym, y_sym, \(x, y) expr(!!y ~ !!x))
models <- map(formulae, \(f) expr(lm(!!f, !!data)))
map(models, \(m) summary(eval(m)))
}
vars <- data.frame(x = c("hp", "hp"),
y = c("mpg", "cyl"))
lm_df(vars, data = mtcars)
```
## Meeting Videos
### Cohort 1
`r knitr::include_url("https://www.youtube.com/embed/tbByqsRRvdE")`
### Cohort 2
`r knitr::include_url("https://www.youtube.com/embed/IXE21pR8EJ0")`
### Cohort 3
`r knitr::include_url("https://www.youtube.com/embed/gxSpz6IePLg")`
### Cohort 4
`r knitr::include_url("https://www.youtube.com/embed/aniKrZrr4aU")`
### Cohort 5
`r knitr::include_url("https://www.youtube.com/embed/klcpEb5ZBSM")`
### Cohort 6
`r knitr::include_url("https://www.youtube.com/embed/OBodjc80y-E")`
<details>
<summary> Meeting chat log </summary>
```
01:02:07 Trevin: Yeah, that was a great workshop
01:02:18 Trevin: Glad they posted the resources online
01:06:39 Trevin: Thank you!
```
</details>
### Cohort 7
`r knitr::include_url("https://www.youtube.com/embed/8LPw_VTBsmQ")`
<details>
<summary>Meeting chat log</summary>
```
00:50:48 Stone: https://www.r-bloggers.com/2018/10/quasiquotation-in-r-via-bquote/
00:58:26 iPhone: See ya next week!
```
</details>
`r knitr::include_url("https://www.youtube.com/embed/g77Jfl_xrXM")`
<details>
<summary>Meeting chat log</summary>
```
00:55:22 collinberke: https://rlang.r-lib.org/reference/embrace-operator.html?q=enquo#under-the-hood
```
</details>