-
Notifications
You must be signed in to change notification settings - Fork 0
/
Quotation.Rmd
622 lines (417 loc) · 14 KB
/
Quotation.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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
# Quasiquotation
```{r Quotation-1, include = FALSE}
source("common.R")
```
Attaching the needed libraries:
```{r Quotation-2, warning=FALSE, message=FALSE}
library(rlang)
library(purrr)
library(lobstr)
library(dplyr)
library(ggplot2)
```
## Motivation (Exercises 19.2.2)
---
**Q1.** For each function in the following base R code, identify which arguments are quoted and which are evaluated.
```{r Quotation-3, results = FALSE, message=FALSE, warning=FALSE}
library(MASS)
mtcars2 <- subset(mtcars, cyl == 4)
with(mtcars2, sum(vs))
sum(mtcars2$am)
rm(mtcars2)
```
**A1.** To identify which arguments are quoted and which are evaluated, we can use the trick mentioned in the book:
> If you’re ever unsure about whether an argument is quoted or evaluated, try executing the code outside of the function. If it doesn’t work or does something different, then that argument is quoted.
- `library(MASS)`
The `package` argument in `library()` is quoted:
```{r Quotation-4, error=TRUE}
library(MASS)
MASS
```
- `subset(mtcars, cyl == 4)`
The argument `x` is evaluated, while the argument `subset` is quoted.
```{r Quotation-5, error=TRUE}
mtcars2 <- subset(mtcars, cyl == 4)
invisible(mtcars)
cyl == 4
```
- `with(mtcars2, sum(vs))`
The argument `data` is evaluated, while `expr` argument is quoted.
```{r Quotation-6, error=TRUE}
with(mtcars2, sum(vs))
invisible(mtcars2)
sum(vs)
```
- `sum(mtcars2$am)`
The argument `...` is evaluated.
```{r Quotation-7, error=TRUE}
sum(mtcars2$am)
mtcars2$am
```
- `rm(mtcars2)`
The trick we are using so far won't work here since trying to print `mtcars2` will always fail after `rm()` has made a pass at it.
```{r Quotation-8, error=TRUE}
rm(mtcars2)
```
We can instead look at the docs for `...`:
> ... the objects to be removed, as names (unquoted) or character strings (quoted).
Thus, this argument is not evaluated, but rather quoted.
---
**Q2.** For each function in the following tidyverse code, identify which arguments are quoted and which are evaluated.
```{r Quotation-9, eval = FALSE}
library(dplyr)
library(ggplot2)
by_cyl <- mtcars %>%
group_by(cyl) %>%
summarise(mean = mean(mpg))
ggplot(by_cyl, aes(cyl, mean)) +
geom_point()
```
**A2.** As seen in the answer for **Q1.**, `library()` quotes its first argument:
```{r Quotation-10, eval=FALSE}
library(dplyr)
library(ggplot2)
```
In the following code:
- `%>%` (lazily) evaluates its argument
- `group_by()` and `summarise()` quote their arguments
```{r Quotation-11}
by_cyl <- mtcars %>%
group_by(cyl) %>%
summarise(mean = mean(mpg))
```
In the following code:
- `ggplot()` evaluates the `data` argument
- `aes()` quotes its arguments
```{r Quotation-12}
ggplot(by_cyl, aes(cyl, mean)) +
geom_point()
```
---
## Quoting (Exercises 19.3.6)
---
**Q1.** How is `expr()` implemented? Look at its source code.
**A1.** Looking at the source code, we can see that `expr()` is a simple wrapper around `enexpr()`, and captures and returns the user-entered expressions:
```{r Quotation-13}
rlang::expr
```
For example:
```{r Quotation-14}
x <- expr(x <- 1)
x
```
In its turn, `enexpr()` calls native code:
```{r}
rlang::enexpr
```
---
**Q2.** Compare and contrast the following two functions. Can you predict the output before running them?
```{r Quotation-15, results = FALSE}
f1 <- function(x, y) {
exprs(x = x, y = y)
}
f2 <- function(x, y) {
enexprs(x = x, y = y)
}
f1(a + b, c + d)
f2(a + b, c + d)
```
**A2.** The `exprs()` captures and returns the expressions specified by the developer instead of their values:
```{r Quotation-16}
f1 <- function(x, y) {
exprs(x = x, y = y)
}
f1(a + b, c + d)
```
On the other hand, `enexprs()` captures the user-entered expressions and returns their values:
```{r Quotation-17}
f2 <- function(x, y) {
enexprs(x = x, y = y)
}
f2(a + b, c + d)
```
---
**Q3.** What happens if you try to use `enexpr()` with an expression (i.e. `enexpr(x + y)`? What happens if `enexpr()` is passed a missing argument?
**A3.** If you try to use `enexpr()` with an expression, it fails because it works only with `symbol`.
```{r Quotation-18, error=TRUE}
enexpr(x + y)
```
If `enexpr()` is passed a missing argument, it returns a missing argument:
```{r Quotation-19, error=TRUE}
arg <- missing_arg()
enexpr(arg)
is_missing(enexpr(arg))
```
---
**Q4.** How are `exprs(a)` and `exprs(a = )` different? Think about both the input and the output.
**A4.** The key difference between `exprs(a)` and `exprs(a = )` is that the former will return an unnamed list, while the latter will return a named list. This is because the former is interpreted as an unnamed argument, while the latter a named argument.
```{r Quotation-20}
exprs(a)
exprs(a = )
```
In both cases, `a` is treated as a symbol:
```{r Quotation-21}
map_lgl(exprs(a), is_symbol)
map_lgl(exprs(a = ), is_symbol)
```
But, the argument is missing only in the latter case, since only the name but no corresponding value is provided:
```{r Quotation-22}
map_lgl(exprs(a), is_missing)
map_lgl(exprs(a = ), is_missing)
```
---
**Q5.** What are other differences between `exprs()` and `alist()`? Read the documentation for the named arguments of `exprs()` to find out.
**A5.** Here are some additional differences between `exprs()` and `alist()`.
- Names: If the inputs are not named, `exprs()` provides a way to name them automatically using `.named` argument.
```{r Quotation-23}
alist("x" = 1, TRUE, "z" = expr(x + y))
exprs("x" = 1, TRUE, "z" = expr(x + y), .named = TRUE)
```
- Ignoring empty arguments: The `.ignore_empty` argument in `exprs()` gives you a much finer control over what to do with the empty arguments, while `alist()` doesn't provide a way to ignore such arguments.
```{r Quotation-24}
alist("x" = 1, , TRUE, )
exprs("x" = 1, , TRUE, , .ignore_empty = "trailing")
exprs("x" = 1, , TRUE, , .ignore_empty = "none")
exprs("x" = 1, , TRUE, , .ignore_empty = "all")
```
- Names injection: Using `.unquote_names` argument in `exprs()`, we can inject a name for the argument.
```{r Quotation-25}
alist(foo := bar)
exprs(foo := bar, .unquote_names = FALSE)
exprs(foo := bar, .unquote_names = TRUE)
```
---
**Q6.** The documentation for `substitute()` says:
> Substitution takes place by examining each component of the parse tree
> as follows:
>
> * If it is not a bound symbol in `env`, it is unchanged.
> * If it is a promise object (i.e., a formal argument to a function)
> the expression slot of the promise replaces the symbol.
> * If it is an ordinary variable, its value is substituted, unless
> `env` is .GlobalEnv in which case the symbol is left unchanged.
Create examples that illustrate each of the above cases.
**A6.** See below examples that illustrate each of the above-mentioned cases.
> If it is not a bound symbol in `env`, it is unchanged.
Symbol `x` is not bound in `env`, so it remains unchanged.
```{r Quotation-26}
substitute(x + y, env = list(y = 2))
```
> If it is a promise object (i.e., a formal argument to a function)
> the expression slot of the promise replaces the symbol.
```{r Quotation-27}
msg <- "old"
delayedAssign("myVar", msg) # creates a promise
substitute(myVar)
msg <- "new!"
myVar
```
> If it is an ordinary variable, its value is substituted, unless
> `env` is .GlobalEnv in which case the symbol is left unchanged.
```{r Quotation-28}
substitute(x + y, env = env(x = 2, y = 1))
x <- 2
y <- 1
substitute(x + y, env = .GlobalEnv)
```
---
## Unquoting (Exercises 19.4.8)
---
**Q1.** Given the following components:
```{r Quotation-29}
xy <- expr(x + y)
xz <- expr(x + z)
yz <- expr(y + z)
abc <- exprs(a, b, c)
```
Use quasiquotation to construct the following calls:
```{r Quotation-30, eval = FALSE}
(x + y) / (y + z)
-(x + z)^(y + z)
(x + y) + (y + z) - (x + y)
atan2(x + y, y + z)
sum(x + y, x + y, y + z)
sum(a, b, c)
mean(c(a, b, c), na.rm = TRUE)
foo(a = x + y, b = y + z)
```
**A1.** Using quasiquotation to construct the specified calls:
```{r Quotation-31}
xy <- expr(x + y)
xz <- expr(x + z)
yz <- expr(y + z)
abc <- exprs(a, b, c)
expr((!!xy) / (!!yz))
expr(-(!!xz)^(!!yz))
expr(((!!xy)) + (!!yz) - (!!xy))
call2("atan2", expr(!!xy), expr(!!yz))
call2("sum", expr(!!xy), expr(!!xy), expr(!!yz))
call2("sum", !!!abc)
expr(mean(c(!!!abc), na.rm = TRUE))
call2("foo", a = expr(!!xy), b = expr(!!yz))
```
---
**Q2.** The following two calls print the same, but are actually different:
```{r Quotation-32}
(a <- expr(mean(1:10)))
(b <- expr(mean(!!(1:10))))
identical(a, b)
```
What's the difference? Which one is more natural?
**A2.** We can see the difference between these two expression if we convert them to lists:
```{r Quotation-33}
as.list(expr(mean(1:10)))
as.list(expr(mean(!!(1:10))))
```
As can be seen, the second element of `a` is a `call` object, while that in `b` is an integer vector:
```{r Quotation-34}
waldo::compare(a, b)
```
The same can also be noticed in ASTs for these expressions:
```{r Quotation-35}
ast(expr(mean(1:10)))
ast(expr(mean(!!(1:10))))
```
The first call is more natural, since the second one inlines a vector directly into the call, something that is rarely done.
---
## `...` (dot-dot-dot) (Exercises 19.6.5)
---
**Q1.** One way to implement `exec()` is shown below. Describe how it works. What are the key ideas?
```{r Quotation-36}
exec <- function(f, ..., .env = caller_env()) {
args <- list2(...)
do.call(f, args, envir = .env)
}
```
**A1.** The keys ideas that underlie this implementation of `exec()` function are the following:
- It constructs a call using function `f` and its argument `...`, and evaluates the call in the environment `.env`.
- It uses [dynamic dots](https://rlang.r-lib.org/reference/dyn-dots.html) via `list2()`, which means that you can splice arguments using `!!!`, you can inject names using `:=`, and trailing commas are not a problem.
Here is an example:
```{r Quotation-37}
vec <- c(1:5, NA)
args_list <- list(trim = 0, na.rm = TRUE)
exec(mean, vec, !!!args_list, , .env = caller_env())
rm("exec")
```
---
**Q2.** Carefully read the source code for `interaction()`, `expand.grid()`, and `par()`. Compare and contrast the techniques they use for switching between dots and list behaviour.
**A2.** Source code reveals the following comparison table:
| Function | Capture the dots | Handle list input |
| :-------------- | :------------------ | :------------------------------------------------------------------- |
| `interaction()` | `args <- list(...)` | `length(args) == 1L && is.list(args[[1L]])` |
| `expand.grid()` | `args <- list(...)` | `length(args) == 1L && is.list(args[[1L]])` |
| `par()` | `args <- list(...)` | `length(args) == 1L && (is.list(args[[1L]] || is.null(args[[1L]])))` |
All functions capture the dots in a list.
Using these dots, the functions check:
- if a list was entered as an argument by checking the number of arguments
- if the count is 1, by checking if the argument is a list
---
**Q3.** Explain the problem with this definition of `set_attr()`
```{r Quotation-38, error = TRUE}
set_attr <- function(x, ...) {
attr <- rlang::list2(...)
attributes(x) <- attr
x
}
set_attr(1:10, x = 10)
```
**A3.** The `set_attr()` function signature has a parameter called `x`, and additionally it uses dynamic dots to pass multiple arguments to specify additional attributes for `x`.
But, as shown in the example, this creates a problem when the attribute is itself named `x`. Naming the arguments won't help either:
```{r Quotation-39, error = TRUE}
set_attr <- function(x, ...) {
attr <- rlang::list2(...)
attributes(x) <- attr
x
}
set_attr(x = 1:10, x = 10)
```
We can avoid these issues by renaming the parameter:
```{r Quotation-40}
set_attr <- function(.x, ...) {
attr <- rlang::list2(...)
attributes(.x) <- attr
.x
}
set_attr(.x = 1:10, x = 10)
```
---
## Case studies (Exercises 19.7.5)
---
**Q1.** In the linear-model example, we could replace the `expr()` in `reduce(summands, ~ expr(!!.x + !!.y))` with `call2()`: `reduce(summands, call2, "+")`. Compare and contrast the two approaches. Which do you think is easier to read?
**A1.** We can rewrite the `linear()` function from this chapter using `call2()` as follows:
```{r Quotation-41}
linear <- function(var, val) {
var <- ensym(var)
coef_name <- map(seq_along(val[-1]), ~ expr((!!var)[[!!.x]]))
summands <- map2(val[-1], coef_name, ~ expr((!!.x * !!.y)))
summands <- c(val[[1]], summands)
reduce(summands, ~ call2("+", .x, .y))
}
linear(x, c(10, 5, -4))
```
I personally find the version with `call2()` to be much more readable since the `!!` syntax is a bit esoteric.
---
**Q2.** Re-implement the Box-Cox transform defined below using unquoting and `new_function()`:
```{r Quotation-42}
bc <- function(lambda) {
if (lambda == 0) {
function(x) log(x)
} else {
function(x) (x^lambda - 1) / lambda
}
}
```
**A2.** Re-implementation of the Box-Cox transform using unquoting and `new_function()`:
```{r Quotation-43}
bc_new <- function(lambda) {
lambda <- enexpr(lambda)
if (!!lambda == 0) {
new_function(
exprs(x = ),
expr(log(x))
)
} else {
new_function(
exprs(x = ),
expr((x^(!!lambda) - 1) / (!!lambda))
)
}
}
```
Let's try it out to see if it produces the same output as before:
```{r Quotation-44}
bc(0)(1)
bc_new(0)(1)
bc(2)(2)
bc_new(2)(2)
```
---
**Q3.** Re-implement the simple `compose()` defined below using quasiquotation and `new_function()`:
```{r Quotation-45}
compose <- function(f, g) {
function(...) f(g(...))
}
```
**A3.** Following is a re-implementation of `compose()` using quasiquotation and `new_function()`:
```{r Quotation-46}
compose_new <- function(f, g) {
f <- enexpr(f) # or ensym(f)
g <- enexpr(g) # or ensym(g)
new_function(
exprs(... = ),
expr((!!f)((!!g)(...)))
)
}
```
Checking that the new version behaves the same way as the original version:
```{r Quotation-47}
not_null <- compose(`!`, is.null)
not_null(4)
not_null2 <- compose_new(`!`, is.null)
not_null2(4)
```
---
## Session information
```{r Quotation-48}
sessioninfo::session_info(include_base = TRUE)
```