-
Notifications
You must be signed in to change notification settings - Fork 1
/
19_Quasiquotation.Rmd
417 lines (281 loc) · 8.75 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
```{r, echo= FALSE, message=FALSE}
library(rlang)
library(purrr)
```
# Quasiquotation
**Learning objectives:**
- What quasiquotation means
- Why it's important
- Learn some practical uses
## 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.** Except for selected parts which we do want to evaluate! ("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
## Motivation
Simple *concrete* example:
`Cement` is a function that works like `paste` but doesn't need need quotes:
```{r}
cement <- function(...) {
args <- ensyms(...)
paste(purrr::map(args, as_string), collapse = " ")
}
cement(Good, morning, Hadley)
```
What if we wanted to use variables ? This is where 'unquoting' comes in!
```{r}
name = "Bob"
cement(Good, afternoon, !!name)
```
## Nonstandard evaluation {-}
* Functions like `dplyr::filter` use nonstandard evaluation, and quote some of their arguments to help make code more *tidy*.
```{r}
#| eval: FALSE
# `cyl` is written as a bare name--a symbol defined in the global environment
# but `cyl` only exists in the data frame "environment"
# so, `{dplyr}` quotes the argument
dplyr::filter(mtcars, cyl == 4)
```
* You often can detect this if the argument wouldn't work in isolation, for example:
```{r, eval = FALSE}
library(MASS) # this is fine
MASS
#> Error: object MASS not found
```
and
```{r, eval = FALSE}
cyl
#> Error: object 'cyl' not found
```
## Quote
- Expression
```{r}
# for interactive use
rlang::expr(x+y)
# enexpr works on function arguments (looks at internal promise object)
f2 <- function(x) rlang::enexpr(x)
f2(a + b + c)
```
- To capture multiple arguments, use `enexprs()`
```{r}
f <- function(...) enexprs(...)
f(x=1, y= 10 *z)
```
- For symbols, there is `ensym` and `ensyms` which check that the argument is a symbol or string.
## Base R method {-}
* Base R methods do not support unquoting.
* Base R equivalent of `expr` is `quote`
* Base R equivalent of `enexpr` is `substitute` (note that `enexpr` uses `substitute`!)
```{r, eval = FALSE}
enexpr
#>function (arg)
#>{
#> .Call(ffi_enexpr, substitute(arg), parent.frame())
#>}
```
* `bquote()` provides a limited form of quasiquotation, see section 19.5
* `~`, the formula, is a quoting function, discussed in Section 20.3.4
## Unquote
- Unquoting allows you to merge together ASTs with selective evaluation.
- Use `!!` (*inject* operator)
- One argument
```{r}
# quote `-1` as `x`
x <- rlang::expr(-1)
# unquote `x` to substitute its unquoted value
# use bang-bang operator
res = rlang::expr(f(!!x, y))
print(res)
lobstr::ast(!!res)
```
- If the right-hand side of `!!` is a function call, it will evalute the function and insert the results.
```{r}
mean_rm <- function(var) {
var <- ensym(var)
expr(mean(!!var, na.rm = TRUE))
}
expr(!!mean_rm(x) + !!mean_rm(y))
#> mean(x, na.rm = TRUE) + mean(y, na.rm = TRUE)
```
- Multiple arguments, use `!!!` *Splice*
```{r}
xs <- rlang::exprs(1, a, -b)
# unquote multiple arguments
# use bang-bang-bang operator
res=expr(f(!!!xs, y))
res
```
```{r}
lobstr::ast(!!res)
```
## ... (dot-dot-dot)
* !!! is also useful in other places where you have a list of expressions you want to insert into a call.
* Two motivating examples:
List of dataframes you want to `rbind` (a list of arbitrary length)
```{r}
dfs <- list(
a = data.frame(x = 1, y = 2),
b = data.frame(x = 3, y = 4)
)
```
How to supply an argument name indirectly?
```{r}
var <- "x"
val <- c(4, 3, 9)
```
* For the first one, we can use unquote (splice) in `dplyr::bind_rows``
```{r}
dplyr::bind_rows(!!!dfs)
```
This is known 'splatting' in some other langauges (Ruby, Go, Julia). Python calls this argument unpacking (`**kwarg`)
* For the second we need to unquote the left side of an `=`. Tidy eval lets us do this with a special `:=`
```{r}
tibble::tibble(!!var := val)
```
* Functions that have these capabilities are said to have *tidy dots* (or apparently now it is called *dynamic dots*). To get this capability in your own functions, use `list2`!
## Example of `list2()` {-}
```{r}
set_attr <- function(.x, ...) {
attr <- rlang::list2(...)
attributes(.x) <- attr
.x
}
attrs <- list(x = 1, y = 2)
attr_name <- "z"
1:10 %>%
set_attr(w = 0, !!!attrs, !!attr_name := 3) %>%
str()
```
### Exercise from 19.6.5 {-}
What is the problem here?
```{r, eval=FALSE}
set_attr <- function(x, ...) {
attr <- rlang::list2(...)
attributes(x) <- attr
x
}
set_attr(1:10, x = 10)
#> Error in attributes(x) <- attr : attributes must be named
```
## Exec {-}
What about existing functions that don't support tidy dots? Use `exec`
```{r}
arg_name <- "na.rm"
arg_val <- TRUE
exec("mean", 1:10, !!arg_name := arg_val)
```
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)
```
## dots_list {-}
- `list2()` is a wrapper around `dots_list` with the most common defaults:
- `.ignore_empty` : Ignores any empty arguments, lets you use trailing commas in a list
- `.homonyms` : controls what happens when multiple arguments use the same name, `list2()` uses default of `keep`
- `.preserve_empty` controls what do so with empty arguments if they are not ignored.
## 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}
do.call("rbind", dfs)
```
### 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)
}
```
## Map-reduce example {-}
Function that will return an expression corresponding to a linear model.
```{r}
linear <- function(var, val) {
# capture variable as a symbol
var <- ensym(var)
# Create a list of symbols of the form var[[1]], var[[2], etc]
coef_name <- map(seq_along(val[-1]), ~ expr((!!var)[[!!.x]]))
# map over the coefficients and the names to create the terms
summands <- map2(val[-1], coef_name, ~ expr((!!.x * !!.y)))
# Dont forget the intercept
summands <- c(val[[1]], summands)
# Reduce!
reduce(summands, ~ expr(!!.x + !!.y))
}
linear(x, c(10, 5, -4))
#> 10 + (5 * x[[1L]]) + (-4 * x[[2L]])
```
## Creating functions example {-}
* `rlang::new_function()` creates a function from its three components and supports tidy evaluation
* Alternative to function factories.
Example:
```{r}
power <- function(exponent) {
new_function(
exprs(x = ),
expr({
x ^ !!exponent
}),
caller_env()
)
}
power(0.5)
```
Another example, is `graphics::curve` that allows you to plot an expression without creating a function. It could be implemented like this:
```{r}
curve2 <- function(expr, xlim = c(0, 1), n = 100) {
expr <- enexpr(expr)
f <- new_function(exprs(x = ), expr)
x <- seq(xlim[1], xlim[2], length = n)
y <- f(x)
plot(x, y, type = "l", ylab = expr_text(expr))
}
curve2(sin(exp(4 * x)), n = 1000)
```
## Summary {-}
* In this chapter we dove into non-standard evaluation with quasiquotation
* Quasiquotation is useful on its own but in the next chapter we will look at the `quosures` and `data masks` to unleash the full power of *tidy evaluation*!
## 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>