generated from posit-conf-2023/workshop-template
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy path02-functions-02.qmd
686 lines (447 loc) · 12.8 KB
/
02-functions-02.qmd
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
---
title: "useR to programmeR"
subtitle: "Functions 2"
author: "Emma Rand and Ian Lyttle"
format:
revealjs:
theme: [simple, styles.scss]
footer: <https://pos.it/programming-r-conf-2023>
slide-number: true
chalkboard: true
code-link: true
code-line-numbers: false
width: 1600
height: 900
bibliography: references.bib
---
## Learning objectives
In this session, we will discuss:
::: incremental
- embracing `{{}}` for `<data-masking>` functions
- tidyverse style and design of functions
- the joys of side-effects
:::
. . .
<hr>
For coding, we will use `r-programming-exercises`:
- `R/functions-02-01-embrace.R`, etc.
- with each new file, restart R.
## Plot functions: Motivation
```{r}
library("tidyverse")
```
Sometimes, you want to generalize a certain type of plot - let's say a histogram:
``` r
diamonds |>
ggplot(aes(x = carat)) +
geom_histogram(binwidth = 0.1)
diamonds |>
ggplot(aes(x = carat)) +
geom_histogram(binwidth = 0.05)
```
"I want choose only the data, variable, and bin-width"
## Function
`aes()` is a data-masking function; you can embrace 🤗
- pass "bare-name" variables for data-frames
- look for `<data-masking>` in help
```{r}
#| output: false
histogram <- function(df, var, binwidth = NULL) {
df |>
ggplot(aes(x = {{ var }})) +
geom_histogram(binwidth = binwidth)
}
histogram(diamonds, carat, 0.1)
```
## Our turn
Complete this function yourself:
``` r
histogram <- function(df, var, binwidth = NULL) {
df |>
ggplot(aes()) +
geom_histogram(binwidth = binwidth)
}
```
- Try with other `df` and `var`, e.g. `starwars`, `mtcars`.
- Using *this* function *as is*, how can you:
- add `theme_minimal()`?
- fill the bars with `"steelblue"`?
## Our turn (solution)
Adding a theme: `histogram()` returns a `ggplot` object, so you can add a theme in the "usual" way:
```{r}
histogram(starwars, height) + theme_minimal()
```
## Our turn (solution)
*As is*, there is no easy way to specify `"steelblue"`.
. . .
However, you can build an escape hatch.
`...` are called "dot-dot-dot" or "dots".
. . .
``` r
# `...` passed to `geom_histogram()`
histogram <- function(df, var, ..., binwidth = NULL) {
df |>
ggplot(aes(x = {{var}})) +
geom_histogram(binwidth = binwidth, ...)
}
```
Passes unspecified arguments from your function to another (tell your users where).
. . .
[Tidyverse Design Guide](https://design.tidyverse.org/dots-after-required.html) has more details.
## Our turn (continued)
Incorporate dot-dot-dot into `histogram()`:
``` r
histogram <- function(df, var, ..., binwidth = NULL) {
df |>
ggplot(aes(x = {{var}})) +
geom_histogram(binwidth = binwidth, ...)
}
```
Try, e.g.:
``` r
histogram(starwars, height, binwidth = 5, fill = "steelblue")
```
## Tradeoffs
You write a function to make some things easier.
. . .
The cost is that some things become more difficult.
. . .
This is unavoidable, the best you can do is be deliberate about what you make easier and more difficult.
## Labelling
How to build a string, using variable-names and values?
. . .
`rlang::englue()` was built for this purpose:
- embrace 🤗 variable-names: `{{}}`
- glue values: `{}`
. . .
```{r}
temp <- function(varname, value) {
rlang::englue("You chose varname: {{ varname }} and value: {value}")
}
temp(val, 0.4)
```
## Your turn
Adapt `histogram()` to include a title that describes:
- which `var` is binned, and the `binwidth`
``` r
histogram <- function(df, var, ..., binwidth = NULL) {
df |>
ggplot(aes(x = {{ var }})) +
geom_histogram(binwidth = binwidth, ...) +
labs(
title = rlang::englue("")
)
}
```
Try:
``` r
histogram(starwars, height, binwidth = 5)
histogram(starwars, height) # "extra credit"
```
## Your turn (solution)
```{r}
#| output: false
histogram <- function(df, var, ..., binwidth = NULL) {
df |>
ggplot(aes(x = {{ var }})) +
geom_histogram(binwidth = binwidth, ...) +
labs(
title = rlang::englue(
"Histogram of {{ var }}, with binwidth {binwidth %||% 'default'}"
)
)
}
histogram(starwars, height, binwidth = 5)
```
## Mixing in other tidyverse functions
Your function can also include pre-processing of data.
```{r}
sorted_bars <- function(df, var) {
df |>
mutate({{ var }} := {{ var }} |> fct_infreq() |> fct_rev()) |>
ggplot(aes(y = {{ var }})) +
geom_bar()
}
sorted_bars(diamonds, clarity)
```
## Mixing in other tidyverse functions
Your function can also include pre-processing of data.
``` r
sorted_bars <- function(df, var) {
df |>
mutate({{ var }} := {{ var }} |> fct_infreq() |> fct_rev()) |>
ggplot(aes(y = {{ var }})) +
geom_bar()
}
```
::: incremental
- If using `{{ }}` to specify a new column, use `:=`, not `=`.
- `fct_infreq()` reorders by decreasing frequency.
- `fct_rev()` reverses order, as y-axis starts at bottom.
- **Our turn**: let's try it
:::
## Summary (so far)
::: incremental
- use embracing `{{}}` to interpolate bare column-names
- function receiving the "embracing" has to be aware
- look for `<data-masking>` in the help
- use `rlang::englue()` to interpolate variables `{{}}` and values `{}`
- `...` is a useful "escape hatch" in function design:
- put after required args, and before details
- tell your users where the dots are going
:::
## Design and style
Restart R, open `functions-02-02-style.R`
. . .
<hr>
Use descriptive name, usually starts with a verb, unless it returns a well-known noun.
. . .
`mutate()`: verb, describes what it does
`median()`: noun, describes what it returns
## Order of arguments
- **required**: arguments without default values
- **dots**: can be passed on functions that your function calls
- **optional**: arguments with default values
. . .
Tidyverse Design:
- [Position of dots](https://design.tidyverse.org/dots-after-required.html)
- [Hadley's *first* Substack article](https://tidydesign.substack.com/p/argument-ordering)
## Order of arguments
Our histogram function:
```{r}
histogram <- function(df, var, ..., binwidth = NULL) {
df |>
ggplot(aes(x = {{var}})) +
geom_histogram(binwidth = binwidth, ...)
}
```
- **required**: `df`, `var`
- **dots**: `...`
- **optional**: `binwidth`
## Order of arguments
```{r}
histogram <- function(df, var, ..., binwidth = NULL) {
df |>
ggplot(aes(x = {{ var }})) +
geom_histogram(binwidth = binwidth, ...)
}
```
Why *optional* after *dots*?
- user must name *optional* arguments, in this case `binwidth`.
- makes code easier to read when *optional* arguments used.
- more reasoning given in the [Tidyverse design guide](https://design.tidyverse.org/dots-position.html).
## Namespacing functions
When we write `filter()`, do we mean...
::: incremental
- `dplyr::filter()`?
- `stats::filter()`?
:::
. . .
Three ways to sort this out:
::: incremental
- `library("conflicted")`, suitable for R scripts
- `package::function()`, used in package functions
- `#' @importFrom`, also used (sparingly) in packages
:::
## 📦 conflicted
``` r
library("conflicted")
```
`{conflicted}` lets you know when you use a function that exists two-or-more packages that you've loaded.
. . .
To avoid conflicts, declare a preference:
``` r
# put in a conspicuous place, near the top of your script
conflicts_prefer(dplyr::filter)
```
## Your turn
In `functions-02-02-style.R`:
``` r
library("tidyverse")
mtcars |> filter(cyl == 6)
```
- run it as-is
- add `library("conflicted")`, run again
- add a `conflicts_prefer()` directive
## `package::function()`
This is the usual way when writing a function for a package:
``` r
histogram <- function(df, var, ..., binwidth = NULL) {
df |>
ggplot2::ggplot(ggplot2::aes(x = {{ var }})) +
ggplot2::geom_histogram(binwidth = binwidth, ...)
}
```
::: incremental
- makes it very clear where you are getting the function from
- can be verbose, especially if calling an external function often
:::
. . .
There is a balance to be struck.
## `#' @importFrom`
When you have a *lot* of calls to a given external function
Put this in `{packagename}-package.R`:
``` r
#' @importFrom ggplot2 ggplot aes geom_histogram
NULL
```
. . .
Alternatively, from the R command prompt:
``` r
usethis::use_import_from("ggplot2", c("ggplot", "aes", "geom_histogram"))
```
## `#' @importFrom`
``` r
histogram <- function(df, var, ..., binwidth = NULL) {
df |>
ggplot(aes(x = {{ var }})) +
geom_histogram(binwidth = binwidth, ...)
}
```
Makes your code less verbose, but also less transparent
. . .
**To mitigate**:
- put all your `@importFrom` in one conspicuous file: `{packagename}-package.R`
- use judiciously
## Design and style references
[R for Data Science](https://r4ds.hadley.nz/functions.html#style)
[Tidyverse Style Guide](https://style.tidyverse.org/functions.html)
[Tidyverse Design Guide](https://design.tidyverse.org/dots-position.html)
[Tidydesign Substack (Hadley)](https://tidydesign.substack.com/)
Also, look at tidyverse code at GitHub (my favorite is [{usethis}](https://github.com/r-lib/usethis/))
## Side effects
Restart R, open `functions-02-03-side-effects.R`
. . .
<hr>
**Pure function**:
- Returns a value that depends only on its inputs, e.g. `sum()`
. . .
**Uses side effects**:
- Depends on something other than inputs, e.g. `read.csv()`
- Or, makes a change in the environment, e.g. `print()`
## Pure function
``` r
add <- function(x, y) {
x + y
}
```
The return value depends *only* on the inputs.
Easier to test.
## Uses side effects
Side-effects can slow down your function:
- it can be costly to read/write to disk, print to the screen.
. . .
Depending on side effects can introduce uncertainty:
- are you *certain* of what `file.csv` contains?
. . .
Side effects aren't necessarily bad, but you need to take them into account:
- need to take care when testing.
## Your turn
Discuss with your neighbor, are these function-calls are pure, or do they use side effects?
In `functions-02-03-side-effects.R`:
``` r
x <- prod(1, 2, 3)
x <- print("Hello")
x <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point()
x <- sort(c("apple", "Banana", "candle"))
```
## Our turn: checking locale
Can be useful to consult `devtools::session_info()`:
```{r}
# using `info = "platform"` to fit output on screen
devtools::session_info(info = "platform")
```
## Manage side effects using 📦 withr
Side effects can include:
::: incremental
- modifying environment: `Sys.setenv()`
- modifying options: `options()`
- setting random seed: `set.seed()`
- setting working directory: `setwd()`
- creating and writing to a temporary file
:::
. . .
{withr} makes it a lot easier to "leave no footprints".
## Our turn: modifying locale
`sort()` uses locale (environment) for string-sorting rules
```{r}
#| collapse: true
(temp <- Sys.getlocale("LC_COLLATE"))
sort(c("apple", "Banana", "candle"))
```
. . .
<hr>
```{r}
#| collapse: true
Sys.setlocale("LC_COLLATE", "C")
sort(c("apple", "Banana", "candle"))
Sys.setlocale("LC_COLLATE", temp)
```
## Our turn: setting within call
To temporarily set locale:
```{r}
#| collapse: true
withr::with_locale(
new = list(LC_COLLATE = "C"),
sort(c("apple", "Banana", "candle"))
)
Sys.getlocale("LC_COLLATE")
```
## Our turn: setting only within scope
```{r}
#| collapse: true
c_sort <- function(...) {
# set only within function block
withr::local_locale(list(LC_COLLATE = "C"))
sort(...)
}
c_sort(c("apple", "Banana", "candle"))
Sys.getlocale("LC_COLLATE")
```
*Within curly brackets* applies to function blocks, it also applies to {testthat} blocks.
## But what about dplyr?
::: incremental
- `?dplyr::arrange()`
- `arrange()` uses the `"C"` locale by default
:::
. . .
<hr>
```{r}
tibble(text = c("apple", "Banana", "candle")) |>
arrange(text)
```
## Your turn
```{r}
library("testthat")
test_that("mtcars has expected columns", {
expect_type(mtcars$cy, "double")
})
```
This passes, but R is doing partial matching on the `$`.
Modify `test_that()` block to warn on partial matching.
You can get the current setting using:
```{r}
getOption("warnPartialMatchDollar")
```
Hint: use `withr::local_option()`.
## Your turn (solution)
```{r}
test_that("mtcars has expected columns", {
withr::local_options(list(warnPartialMatchDollar = TRUE))
expect_type(mtcars$cy, "double")
})
```
And yet...
```{r}
getOption("warnPartialMatchDollar")
```
## Summary
You can use tidy evaluation in {ggplot2} to specify aesthetics, add labels, and include {dplyr} preprocessing:
- embracing `{{}}` for `<data-masking>` functions
- be aware of `<tidy-select>` functions, work differently
. . .
<hr>
Using tidyverse style and design can make things easier for you, your users, and *future you*.
. . .
<hr>
Be mindful of side effects, use {withr} to manage global state.