This repository has been archived by the owner on Aug 17, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnse.Rmd
811 lines (656 loc) · 23.8 KB
/
nse.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
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
# Non-Standard Evaluation {#nse}
```{r setup, include=FALSE}
source("etc/common.R")
```
The biggest difference between R and Python is not where R starts counting,
but its use of [lazy evaluation](glossary.html#lazy-evaluation).
Nothing in R truly makes sense until we understand how this works.
## Learning Objectives
- Trace the order of evaluation in function calls.
- Explain what environments and expressions are and how they relate to one another.
- Justify the author's use of ASCII art in the second decade of the 21st Century.
## How does Python evaluate function calls?
Let's start by looking at a small Python program and its output:
```{python py-def-call}
def ones_func(ones_arg):
return ones_arg + " ones"
def tens_func(tens_arg):
return ones_func(tens_arg + " tens")
initial = "start"
final = tens_func(initial + " more")
print(final)
```
When we call `tens_func` we pass it `initial + " more"`;
since `initial` has just been assigned the value `"start"`,
that's the same as calling `tens_func` with `"start more"`.
`tens_func` then calls `ones_func` with `"start more tens"`,
and `ones_func` returns `"start more tens ones"`.
But there's more going on here than that two-sentence summary suggests.
Let's spell out the steps:
```{python py-def-call-details}
def ones_func(ones_arg):
ones_temp_1 = ones_arg + " ones"
return ones_temp_1
def tens_func(tens_arg):
tens_temp_1 = tens_arg + " tens"
tens_temp_2 = ones_func(tens_temp_1)
return tens_temp_2
initial = "start"
global_temp_1 = initial + " more"
final = tens_func(global_temp_1)
print(final)
```
Step 1: we assign `"start"` to `initial` at the global level:
```{r py-step-1, echo=FALSE, fig.cap="Python Step 1"}
if (knitr::is_latex_output()) {
knitr::include_graphics("figures/nse/python-step-01.pdf")
} else {
knitr::include_graphics("figures/nse/python-step-01.svg")
}
```
Step 2: we ask Python to call `tens_func(initial + "more")`,
so it creates a temporary variable to hold the result of the concatenation
*before* calling `tens_func`:
```{r py-step-2, echo=FALSE, fig.cap="Python Step 2"}
if (knitr::is_latex_output()) {
knitr::include_graphics("figures/nse/python-step-02.pdf")
} else {
knitr::include_graphics("figures/nse/python-step-02.svg")
}
```
Step 3: Python creates a new stack frame to hold the call to `tens_func`:
```{r py-step-3, echo=FALSE, fig.cap="Python Step 3"}
if (knitr::is_latex_output()) {
knitr::include_graphics("figures/nse/python-step-03.pdf")
} else {
knitr::include_graphics("figures/nse/python-step-03.svg")
}
```
Note that `tens_arg` points to the same thing in memory as `global_temp_1`,
since Python passes everything by reference.
Step 4: we ask Python to call `ones_func(tens_arg + " tens")`,
so it creates another temporary variable:
```{r py-step-4, echo=FALSE, fig.cap="Python Step 4"}
if (knitr::is_latex_output()) {
knitr::include_graphics("figures/nse/python-step-04.pdf")
} else {
knitr::include_graphics("figures/nse/python-step-04.svg")
}
```
Step 5: Python creates a new stack frame to manage the call to `ones_func`:
```{r py-step-5, echo=FALSE, fig.cap="Python Step 5"}
if (knitr::is_latex_output()) {
knitr::include_graphics("figures/nse/python-step-05.pdf")
} else {
knitr::include_graphics("figures/nse/python-step-05.svg")
}
```
Step 6: Python creates a temporary variable to hold `ones_arg + "ones"`:
```{r py-step-6, echo=FALSE, fig.cap="Python Step 6"}
if (knitr::is_latex_output()) {
knitr::include_graphics("figures/nse/python-step-06.pdf")
} else {
knitr::include_graphics("figures/nse/python-step-06.svg")
}
```
Step 7: Python returns from `ones_func`
and puts its result in yet another temporary variable in `tens_func`:
```{r py-step-7, echo=FALSE, fig.cap="Python Step 7"}
if (knitr::is_latex_output()) {
knitr::include_graphics("figures/nse/python-step-07.pdf")
} else {
knitr::include_graphics("figures/nse/python-step-07.svg")
}
```
Step 8: Python returns from `tens_func`
and puts that call's result in `final`:
```{r py-step-8, echo=FALSE, fig.cap="Python Step 8"}
if (knitr::is_latex_output()) {
knitr::include_graphics("figures/nse/python-step-08.pdf")
} else {
knitr::include_graphics("figures/nse/python-step-08.svg")
}
```
The most important thing here is that Python evaluates expressions *before* it calls functions,
and passes the results of those evaluations to the functions.
This is called [eager evaluation](glossary.html#eager-evaluation),
and is what most widely-used programming languages do.
## How does R evaluate function calls?
In contrast,
R uses [lazy evaluation](glossary.html#lazy-evaluation).
Here's an R program that's roughly equivalent to the Python shown above:
```{r r-def-call}
ones_func <- function(ones_arg) {
paste(ones_arg, "ones")
}
tens_func <- function(tens_arg) {
ones_func(paste(tens_arg, "tens"))
}
initial <- "start"
final <- tens_func(paste(initial, "more"))
print(final)
```
And here it is with the intermediate steps spelled out in a syntax I just made up:
```{r r-def-call-details, eval=FALSE}
ones_func <- function(ones_arg) {
ones_arg.RESOLVE(@tens_func@, paste(tens_arg, "tens"), "start more tens")
ones_temp_1 <- paste(ones_arg, "ones")
return(ones_temp_1)
}
tens_func <- function(tens_arg) {
tens_arg.RESOLVE(@global@, paste(initial, "more"), "start more")
tens_temp_1 <- PROMISE(@tens_func@, paste(tens_arg, "tens"), ____)
tens_temp_2 <- ones_func(paste(tens_temp_1))
return(tens_temp_2)
}
initial <- "start"
global_temp_1 <- PROMISE(@global@, paste(initial, "more"), ____)
final <- tens_func(global_temp_1)
print(final)
```
While the original code looked much like our Python,
the evaluation trace is very different,
and hinges on the fact that
*an expression in a programming language can be represented as a data structure*.
> **What's an Expression?**
>
> An expression is anything that has a value.
> The simplest expressions are literal values like the number 1,
> the string `"stuff"`, and the Boolean `TRUE`.
> A variable like `least` is also an expression:
> its value is whatever the variable currently refers to.
>
> Complex expressions are built out of simpler expressions:
> `1 + 2` is an expression that uses `+` to combine 1 and 2,
> while the expression `c(10, 20, 30)` uses the function `c`
> to create a vector out of the values 10, 20, 30.
> Expressions are often drawn as trees like this:
>
> +
> / \
> 1 2
>
> When Python (or R, or any other language) reads a program,
> it parses the text and builds trees like the one shown above
> to represent what the program is supposed to do.
> Processing that data structure to find its value
> is called [evaluating](glossary.html#evaluation) the expression.
>
> Most modern languages allow us to build trees ourselves,
> either by concatenating strings to create program text
> and then asking the language to parse the result:
>
> left <- '1'
> right <- '2'
> op <- '+'
> combined <- paste(left, op, right)
> tree <- parse(text = combined)
>
> or by calling functions.
> The function-based approach is safer and more flexible;
> see @Wick2019 for details.
Step 1: we assign "start" to `initial` in the [global environment](glossary.html#global-environment):
```{r r-step-1, echo=FALSE, fig.cap="R Step 1"}
if (knitr::is_latex_output()) {
knitr::include_graphics("figures/nse/r-step-01.pdf")
} else {
knitr::include_graphics("figures/nse/r-step-01.svg")
}
```
Step 2: we ask R to call `tens_func(initial + "more")`,
so it creates a [promise](glossary.html#promise) to hold:
- the [environment](glossary.html#environment) we're in (which I'm surrounding with `@`),
- the expression we're passing to the function, and
- the value of that expression (which I'm showing as `____`, since it's initially empty).
```{r r-step-2, echo=FALSE, fig.cap="R Step 2"}
if (knitr::is_latex_output()) {
knitr::include_graphics("figures/nse/r-step-02.pdf")
} else {
knitr::include_graphics("figures/nse/r-step-02.svg")
}
```
and in Step 3,
passes that into `tens_func`:
```{r r-step-3, echo=FALSE, fig.cap="R Step 3"}
if (knitr::is_latex_output()) {
knitr::include_graphics("figures/nse/r-step-03.pdf")
} else {
knitr::include_graphics("figures/nse/r-step-03.svg")
}
```
Crucially,
the promise in `tens_func` remembers that it was created in the [global environment](glossary.html#global-environment):
it will eventually need a value for `initial`,
so it needs to know where to look to find the right one.
Step 4: since the very next thing we ask for is `paste(tens_arg, "tens")`,
R needs a value for `tens_arg`.
To get it,
R evaluates the promise that `tens_arg` refers to:
```{r r-step-4 ,echo=FALSE, fig.cap="R Step 4"}
if (knitr::is_latex_output()) {
knitr::include_graphics("figures/nse/r-step-04.pdf")
} else {
knitr::include_graphics("figures/nse/r-step-04.svg")
}
```
This evaluation happens *after* `tens_func` has been called,
not before as in Python,
which is why this scheme is called "lazy" evaluation.
Once a promise has been resolved,
R uses its value,
and that value never changes.
Steps 5:
`tens_func` wants to call `ones_func`,
so R creates another promise to record what's being passed into `ones_func`:
```{r r-step-5, echo=FALSE, fig.cap="R Step 5"}
if (knitr::is_latex_output()) {
knitr::include_graphics("figures/nse/r-step-05.pdf")
} else {
knitr::include_graphics("figures/nse/r-step-05.svg")
}
```
Step 6:
R calls `ones_func`,
binding the newly-created promise to `ones_arg` as it does so:
```{r r-step-6, echo=FALSE, fig.cap="R Step 6"}
if (knitr::is_latex_output()) {
knitr::include_graphics("figures/nse/r-step-06.pdf")
} else {
knitr::include_graphics("figures/nse/r-step-06.svg")
}
```
Step 7:
R needs a value for `ones_arg` to pass to `paste`,
so it resolves the promise:
```{r r-step-7, echo=FALSE, fig.cap="R Step 7"}
if (knitr::is_latex_output()) {
knitr::include_graphics("figures/nse/r-step-07.pdf")
} else {
knitr::include_graphics("figures/nse/r-step-07.svg")
}
```
Step 8: `ones_func` uses `paste` to concatenate strings:
```{r r-step-8, echo=FALSE, fig.cap="R Step 8"}
if (knitr::is_latex_output()) {
knitr::include_graphics("figures/nse/r-step-08.pdf")
} else {
knitr::include_graphics("figures/nse/r-step-08.svg")
}
```
Step 9: `ones_func` returns:
```{r r-step-9, echo=FALSE, fig.cap="R Step 9"}
if (knitr::is_latex_output()) {
knitr::include_graphics("figures/nse/r-step-09.pdf")
} else {
knitr::include_graphics("figures/nse/r-step-09.svg")
}
```
Step 10: `tens_func` returns:
```{r r-step-10, echo=FALSE, fig.cap="R Step 10"}
if (knitr::is_latex_output()) {
knitr::include_graphics("figures/nse/r-step-10.pdf")
} else {
knitr::include_graphics("figures/nse/r-step-10.svg")
}
```
We got the same answer as we did in Python,
but in a significantly different way.
Each time we passed something into a function,
R created a promise to record what it was and where it came from,
and then resolved the promise when the value was needed.
R *always* does this—if we call:
```{r call-sign, eval=FALSE}
sign(2)
```
then behind the scenes,
R is creating a promise and passing it to `sign`,
where it is automatically resolved to get the number 2 when its value is needed.
(If I wanted to be thorough,
I would have shown the promises passed into `paste` at each stage of execution above.)
## Why is lazy evaluation useful?
R's lazy evaluation seems pointless
if it always produces the same answer as Python's eager evaluation,
but it doesn't have to.
To see how powerful lazy evaluation can be,
let's create an expression of our own:
```{r create-expr}
my_expr <- expr(red)
```
Displaying the value of `my_expr` isn't very exciting:
```{r show-expr}
my_expr
```
but what kind of thing is it?
```{r type-of-expr}
typeof(my_expr)
```
A symbol is a kind of expression.
It is not a string (though strings can be converted to symbols and symbols to strings)
nor is it a value—not yet.
If we try to get the value it refers to, R displays an error message:
```{r eval-expr-error, error=TRUE}
eval(my_expr)
```
We haven't created a variable called `red`,
so R cannot evaluate an expression that asks for it.
But what if we create such a variable now and then re-evaluate the expression?
```{r eval-after-var-def}
red <- "this is red"
eval(my_expr)
```
More usefully,
what if we create something that has a value for `red`:
```{r create-tibble}
color_data <- tribble(
~red, ~green,
1, 10,
2, 20
)
color_data
```
and then ask R to evaluate our expression in the [context](glossary.html#context) of that tibble:
```{r eval-with-context}
eval(my_expr, color_data)
```
When we do this,
`eval` looks for definitions of variables in the data structure we've given it—in this case,
the tibble `color_data`.
Since that tibble has a column called `red`,
`eval(my_expr, color_data)` gives us that column.
This may not seem life-changing yet,
but being able to pass expressions around
and evaluate them in contexts of our choosing allows us to seem very clever indeed.
For example,
let's create another expression:
```{r expr-add-red-green}
add_red_green <- expr(red + green)
typeof(add_red_green)
```
The type of `add_red_green` is `language` rather than `symbol` because it contains more than just a single symbol,
but it's still an expression,
so we can evaluate it in the context of our data frame:
```{r eval-add-red-green}
eval(add_red_green, color_data)
```
Still not convinced?
Have a look at this function:
```{r def-run-many-checks}
run_many_checks <- function(data, ...) {
conditions <- list(...)
checks <- vector("list", length(conditions))
for (i in seq_along(conditions)) {
checks[[i]] <- eval(conditions[[i]], data)
}
checks
}
```
`run_many_checks` takes a tibble and some logical expressions,
evaluates each expression in turn,
and returns a list of results:
```{r call-many-checks}
run_many_checks(color_data, expr(0 < red), expr(red < green))
```
We can take it one step further and simply report whether all the checks passed or not:
```{r report-run-all-checks}
run_all_checks <- function(data, ...) {
conditions <- list(...)
checks <- vector("logical", length(conditions))
for (i in seq_along(conditions)) {
checks[[i]] <- all(eval(conditions[[i]], data))
}
all(checks)
}
run_all_checks(color_data, expr(0 < red), expr(red < green))
```
This is cool, but typing `expr(...)` over and over is kind of clumsy.
It also seems superfluous,
since we know that arguments aren't evaluated before they're passed into functions.
Can we get rid of this and write something that does this?
```{r desired-check-call, eval=FALSE}
run_all_checks(color_data, 0 < red, red < green)
```
The answer is going to be "yes",
but it's going to take a bit of work.
> **Square Brackets… Why'd It Have to Be Square Brackets?**
>
> Before we go there,
> a word (or code snippet) of warning.
> The first version of `run_many_checks` essentially did this:
>
> ```{r mistaken-condition, eval=FALSE}
> conditions <- list(expr(red < green))
> eval(conditions[1], color_data)
> ```
>
> What I did wrong was use `[` instead of `[[`,
> which meant that `conditions[1]` was not an expression—it was a list containing a single expression.
> It turns out that evaluating a list containing an expression produces a list of expressions rather than an error,
> which is so helpful that it only took me an hour to figure out my mistake.
## What is tidy evaluation?
Our goal is to write something that looks like it belongs in the tidyverse.
We want to be able to write this:
```{r show-better-check-all, eval=FALSE}
check_all(color_data, 0 < red, red < green)
```
without calling `expr` to quote our expressions explicitly.
For simplicity's sake,
our first attempt only handles a single expression:
```{r def-check-naive}
check_naive <- function(data, test) {
eval(test, data)
}
```
When we try it, it fails:
```{r check-naive-fails, error=TRUE}
check_naive(color_data, red != green)
```
This actually makes sense:
by the time we reach the call to `eval`,
`test` refers to a promise that represents the value of `red != green` in the global environment.
Promises are not expressions—each promise contains an expression,
but it also contains an environment and a copy of the expression's value (if it has ever been calculated).
As a result,
when R sees the call to `eval` inside `check_naive`
it automatically tries to resolve the promise that contains `left != right`,
and fails because there are no variables with those names in the global environment.
So how can we get the expression out of the promise without triggering evaluation?
One way is to use a function called `substitute`:
```{r check-using-substitute}
check_using_substitute <- function(data, test) {
subst_test <- substitute(test)
eval(subst_test, data)
}
check_using_substitute(color_data, red != green)
```
However,
`substitute` is frowned upon because it does one thing when called interactively on the command line
and something else when called inside a function.
Instead,
we can use a function called `enquo` from the rlang package.
`enquo` returns an object called a [quosure](glossary.html#quosure)
that contains only an unevaluated expression and an environment:
```{r check-with-enquo-fail}
check_using_enquo <- function(data, test) {
q_test <- enquo(test)
eval(q_test, data)
}
check_using_enquo(color_data, red != green)
```
Ah: a quosure is a structured object,
so evaluating it just gives it back to us in the same way that evaluating `2` or `"hello"` would.
What we want to `eval` is the expression inside the quosure,
which we can get using `quo_get_expr`:
```{r check-with-enquo-success}
check_using_quo_get_expr <- function(data, test) {
q_test <- enquo(test)
eval(quo_get_expr(q_test), data)
}
check_using_quo_get_expr(list(left = 1, right = 2), left != right)
```
Enquoting and evaluating expressions is done so often in the tidyverse
that rlang provides a shortcut called `{{..}}`:
```{r}
max_of_var <- function(data, the_var) {
data %>%
group_by({{ the_var }}) %>%
summarize(maximum = max({{ the_var }}))
}
max_of_var(color_data, red)
```
We can use this to write a function `run_two_checks` that runs two checks on some data:
```{r}
run_two_checks <- function(data, first_check, second_check) {
first_result <- data %>%
transmute(temp = {{ first_check }}) %>%
pull(temp) %>%
all()
second_result <- data %>%
transmute(temp = {{ second_check }})%>%
pull(temp) %>% all()
first_result && second_result
}
run_two_checks(color_data, 0 < red, red < green)
```
That's much easier to follow than a bunch of `enquo` and `eval` calls,
but what if we want to handle an arbitrary number of checks?
Our first attempt is this:
```{r error=TRUE}
new_colors <- tribble(
~yellow, ~violet,
1, 10,
2, 20
)
run_all_checks <- function(data, ...) {
conditions <- list(...)
result = TRUE
for (i in seq_along(conditions)) {
cond = conditions[[i]]
result <- result && data %>% transmute(temp = {{cond}}) %>% pull(temp) %>% all()
}
result
}
run_all_checks(new_colors, 0 < yellow, violet < yellow)
```
This code fails because the call to `list(...)` tries to evaluate the expressions in `...`
when adding them to the list.
What we need to use instead is `enquos`,
which does what `enquo` does but on `...`:
```{r}
run_all_checks <- function(data, ...) {
conditions <- enquos(...)
result = TRUE
for (i in seq_along(conditions)) {
cond = conditions[[i]]
result <- result && data %>%
transmute(temp = {{ cond }}) %>%
pull(temp) %>%
all()
}
result
}
run_all_checks(new_colors, 0 < yellow, violet < yellow)
```
## What if I truly desire to venture into the depths?
We will occasionally need to go one level deeper in tidy evaluation.
Our first attempt (which only handles a single test) is going to fail on purpose
to demonstrate a common mistake:
```{r deliberate-failure, error=TRUE}
check_without_quoting_test <- function(data, test) {
data %>% transmute(result = test) %>% pull(result) %>% all()
}
check_without_quoting_test(color_data, yellow < violet)
```
That failed because we're not enquoting the test.
Let's modify it the code to enquote and then pass in the expression:
```{r another-failure, error=TRUE}
check_without_quoting_test <- function(data, test) {
q_test <- enquo(test)
x_test <- quo_get_expr(q_test)
data %>% transmute(result = x_test) %>% pull(result) %>% all()
}
check_without_quoting_test(new_colors, yellow < violet)
```
Damn—we thought this one had a chance.
The problem is that when we say `result = x_test`,
what actually gets passed into `transmute` is a promise containing an expression.
Somehow,
we need to prevent R from doing that promise wrapping.
This brings us to `enquo`'s partner `!!`,
which we can use to [splice](glossary.html#splice) the expression in a quosure into a function call.
`!!` is pronounced "bang bang" or "oh hell",
depending on how your day is going.
It only works in contexts like function calls where R is automatically quoting things for us,
but if we use it then,
it does exactly what we want:
```{r check-using-bang-bang, error=TRUE}
check_using_bangbang <- function(data, test) {
q_test <- enquo(test)
data %>% transmute(result = !!q_test) %>% pull(result) %>% all()
}
check_using_bangbang(new_colors, yellow < violet)
```
We are almost in a state of grace.
The two rules we must follow are:
1. Use `enquo` to enquote every argument that contains an unevaluated expression.
2. Use `!!` when passing each of those arguments into a tidyverse function.
```{r check-all-complete}
check_all <- function(data, ...) {
tests <- enquos(...)
result <- TRUE
for (t in tests) {
result <- result && data %>%
transmute(result = !!t) %>%
pull(result) %>%
all()
}
result
}
check_all(new_colors, 0 < yellow, yellow < violet)
```
And just to make sure that it fails when it's supposed to:
```{r check-all-pass}
check_all(new_colors, yellow == violet)
```
Backing up a bit,
`!!` works because there are
[two kinds of functions in R](https://tidyeval.tidyverse.org/getting-up-to-speed.html#whats-special-about-quoting-functions):
[evaluating functions](glossary.html#evaluating-function) and
[quoting functions](glossary.html#quoting-function).
Evaluating functions take arguments as values—they're what most of us are used to working with.
Quoting functions, on the other hand, aren't passed the values of expressions, but the expressions themselves.
When we write `color_data$red`, the `$` function is being passed `color_data` and the quoted expression `red`.
This is why we can't use variables as field names with `$`:
```{r cannot-use-variables-with-dollar, error=TRUE}
the_string_red <- "red"
color_data$the_string_red
```
The square bracket operators `[` and `[[`, on the other hand,
are evaluating functions,
so we can give them a variable containing a column name and get either a single-column tibble:
```{r can-use-variables-with-brackets-1}
color_data[the_string_red] # single square brackets
```
or a naked vector:
```{r can-use-variables-with-brackets-2}
color_data[[the_string_red]] # double square brackets
```
## Is it worth it?
Delayed evaluation and quoting are confusing for two reasons:
1. They expose machinery that most programmers have never had to deal with before (and might not even have known existed).
It's rather like learning to drive an automatic transmission and then switching to a manual one—all of a sudden
you have to worry about a gear shift and a clutch.
2. R's built-in tools don't behave as consistently as they could,
and the core functions provided by the tidverse as alternatives use variations on a small number of names:
`quo`, `quote`, and `enquo` might all appear on the same page.
That said,
being able to pass column names to functions without wrapping them in strings is very useful,
and many powerful tools (such as using formulas in models)
rely on taking unevaluated expressions apart and rearranging them.
If you would like to know more,
or check that what you now think you understand is accurate,
[this tutorial][lyttle-tutorial] is a good next step.
## Key Points
```{r keypoints, child="keypoints/nse.md"}
```
```{r links, child="etc/links.md"}
```