-
Notifications
You must be signed in to change notification settings - Fork 5
/
09-R-packages.qmd
596 lines (377 loc) · 12.3 KB
/
09-R-packages.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
---
title: "Building `R` Packages"
format:
revealjs:
theme: _extensions/metropolis-theme/metropolis.scss
chalkboard: true
logo: /images/ScPo-logo.png
footer: "[SciencesPo Intro To Programming 2024](https://floswald.github.io/ScPoProgramming/)"
incremental: false
code-line-numbers: false
highlight-style: github
slide-number: true
author: Florian Oswald
subtitle: "[SciencesPo Intro To Programming 2024](https://floswald.github.io/ScPoProgramming/)"
date: today
date-format: "D MMMM, YYYY"
---
## R and Packages
::: {.columns}
::: {.column width=45%}
::: {.callout-tip}
# Questions
1. Why write our _own_ `R` package?
2. How to create an `R` package?
3. What are _unit tests_?
:::
:::
::: {.column width=45%}
::: {.callout-note}
# Objectives
* Learn the `RStudio`-powered package development workflow.
* Create a package, and test it.
* Publish the package to github.
* Publish the package docs as a self-contained website.
:::
:::
:::
---
## R and Packages
* We have been using `R` packages all the time.
* Each time we say `library(xyz)` we are using *external* code provided in the `xyz` package.
* You can write **your own** packages.
. . .
::: {.callout-tip}
# What's the point of Packages?
1. Extend `R` functionality.
2. **for researchers**: key tool to ensure _reproducibilty_ of findings
3. **for researchers**: key tool to _organize_ code in team work
:::
* Let's go through some material from the [`r-pkgs`](https://r-pkgs.org) book!
---
## Building a Toy Package
::: {.columns}
::: {.column width=45%}
### `RStudio` for the win
* We do this in `RStudio`
* we use the `devtools` package
* check you have a recent version:
```{r}
#| echo: true
packageVersion("devtools")
```
* if not - reinstall.
:::
::: {.column width=45%}
### Let's Do it!
```{r}
#| echo: true
#| eval: true
library(devtools)
# create a package `here`
create_package("~/toypackage")
```
* You see Rstudio jumps to that location
:::
:::
---
## Adding Git
* Of course we want to track our package with `git`.
* We use functions from the `usethis` package. This is loaded by default when attaching the `devtools` package (`use_git` is part of `usethis`...)
```{r}
#| eval: true
#| echo: true
#|
library(devtools)
use_git()
```
* Say `Yes` to everything ✌️
---
## Adding Code
* We add `R` _source_ code in the `R/` folder.
* Create as many `.R` files as you want.
* It's good practice to organize tests accompanying source files.
```{r}
#| eval: true
#| echo: true
#| message: true
use_r("sayhello")
```
* What's with that `use_test()` thing? 🤔 Let's worry about this later.
---
## Ok, but...Adding Code??
* Let's add a function to the file `R/sayhello.R`:
```r
# Notice I'm using = instead of < - because
# the font of those slides prints it weirdly
hello = function(who){
paste("hello,",who)
}
```
* Now, if this were a simple `R` script, we could `source` the `R/sayhello.R` file into global space and try this out.
* We _don't_ want to do that here though. 🤨
* Instead, we want to _load_ the **package**, which _contains_ our function.
* do `load_all()`:
```r
load_all()
ℹ Loading toypackage
```
---
## Trying out Code
::: {.callout-note}
# `load_all()`
* The `load_all()` function simulates the process of building, installing, and attaching the `toypackage` package.
* This means that **all** the functions you included in the package will become _visible_ in the global scope (in your console)
* This is _not_ in general the case: Later on we will fine-tune which functions are visible to the user, and which ones are not!
:::
* Call the function with your name!
```r
hello("Peter")
[1] "hello, Peter"
```
* Great!
---
## Checking the Package
* `R` has a rigid set of rules for what a package needs to look like.
* What files should be where, their names and permissions, such that the structure is nicely uniform across all R packages.
* Particularly relevant for _official_ packages on [CRAN](https://cran.r-project.org/)
* Do this here often:
```r
check()
```
* This outputs a bunch of things:
1. It actually _builds_ our package in a separate process - immune from our current workspace
2. It runs a battery of checks and returns a report:
```r
0 errors ✔ | 1 warning ✖ | 1 note ✖
```
---
## Editing DESCRIPTION
* Open the `DESCRIPTION` file (or type `Ctrl + .` and start typing `desc`)
* Fill in the obviously missing contents.
### Adding a LICENSE
> [Use a license, any license (Jeff Atwood)](https://blog.codinghorror.com/pick-a-license-any-license/)
Let's
```r
use_mit_license()
```
---
## Documenting with Roxygen
* Go back to the `hello` function, place the cursor inside the function body, and do `Code > Insert Roxygen Skeleton`.
* You'll see something like this:
```r
#' Title
#'
#' @param who
#'
#' @return
#' @export
#'
#' @examples
hello <- function(who){
paste("hello,",who)
}
```
* Each line starting with `#'` is part of the **docstring**.
* The `roxygen` package can _separate_ those blocks from our code, and produce valid `R` documentation for us! 🤯
---
## Building Documentation
* Let's modify the docstring accordingly.
* execute the `document()` function.
* After that, the documentation is visible to us:
```r
?hello
ℹ Rendering development documentation for "hello"
```
* Look in the _Help_ pane in RStudio!
---
## NAMESPACE
* Did you notice the `@export` tag in the docstring?
* when we ran `document()`, roxygen changed the `NAMESPACE` file based upon that tag.
* Go and look at that file!
* The contents of `NAMESPACE` specify what is _visible_ to a user who does `library(toypackage)`.
* Try removing the `@export` tag, and `document()` again. Look back at `NAMESPACE`!
### `check()` again!
```r
check()
0 errors ✔ | 0 warnings ✔ | 0 notes ✔
```
---
## Time to INSTALL the package
* Ok, great. Now we have a minimal package that _works to a certain extent_ 🙂.
* We must _install_ it into our package library, in order to be able to use it like any other package (same as when we did `install.packages("ggplot2")`)
* Notice that `R` installs your packages here:
```{r}
#| echo: true
.libPaths()
```
* We _install_ our package into that location with `install()`
* Look out for the final message:
```r
* DONE (toypackage)
```
👏
---
## New Session - Try it Out!
* Restart Rstudio
* type into the console
```r
library(toypackage)
```
* and then let's see our cool 😎 function:
```r
hello("John Spencer Blues Explosion")
[1] "hello, John Spencer Blues Explosion"
```
* Works! Bingo! 🎉
---
## Automatically Testing Our Code
* We verified ourselves that this _works_.
* We had our own, informal, way to convince ourselves that it works.
* We knew which steps we had to follow until we would conclude that "yes, this works".
. . .
::: {.columns}
::: {.column width=45%}
::: {.callout-caution}
# The Time Factor
If you come back to this in 2 months time you probably
a. won't remember all the steps you have taken (above)
b. won't be able to reproduce what you _tested_ today!
:::
:::
::: {.column width=45%}
::: {.callout-warning}
# The Scale Factor
As your package grows, you will find it hard to come back to all components repeatedly, making sure they all _still_ work as intended (now that they may depend on other parts of your code)
:::
:::
:::
# Unit Testing and Continuous Integration (CI)
---
## Enter **Unit Testing**
* Automatic Unit Testing or [_Continuous Integration_ (CI)](https://en.wikipedia.org/wiki/Continuous_integration) is our best response to this.
* We still have to *design* and *write* the tests, but we can offload the work to **run** the tasks repeatedly, and automatically, to a helpful infrastructure.
```r
library(devtools)
use_testthat()
```
* then
```r
use_test("sayhello")
• Modify 'tests/testthat/test-sayhello.R'
```
---
## Writing Unit Tests
* Ideally, each function in our `R/` folder is _covered_ by a corresponding test.
::: {.callout-important}
# What Is a Test?
The purpose of a **test** is to verify that some part of your code, a function in most cases, works **as intended**.
:::
* Modify `'tests/testthat/test-sayhello.R'` like so
```r
test_that("hello function works", {
who = "James T. Kirk"
expect_equal(hello(who), paste("hello,",who))
})
```
* Ready for 🚀 takeoff?
---
## Running all unit tests
* You can run each test file separately to try it out (you must do `library(testthat)` first)
* It's better practice to test the entire package though:
```r
> test()
ℹ Testing toypackage
Attaching package: ‘testthat’
The following object is masked from ‘package:devtools’:
test_file
✔ | F W S OK | Context
✔ | 1 | sayhello
══ Results ══════════════════════════════════════════════════════
[ FAIL 0 | WARN 0 | SKIP 0 | PASS 1 ]
```
* Celebrate! 🎉 🥳 🎊
## Using _other_ packages
* Most likely our package would depend some _other_ package as well.
* Like we could choose the `export` some of our functions, we now may want to `import` some functions from elsewhere.
* Suppose we want to use the `dplyr` package:
```r
> use_package("dplyr")
✔ Adding 'dplyr' to Imports field in DESCRIPTION
• Refer to functions with `dplyr::fun()`
```
* Let's check the `DESCRIPTION` file to see what happened.
---
## Hook it up to GitHub!
* It's fairly easy to publish our new package to a github repo.
* Let's `use_github()`
```r
use_github()
```
* answer all the prompts and end up here!
![](/images/toypackage.png)
---
## Adding a Readme file
* We know by now that readme files are very important on any git repo.
* Let's add one here as well!
* the `usethis::use_readme_rmd()` function is perfect for this:
```r
usethis::use_readme_rmd()
```
* If we want to automatically run our tests on a remote server called _github actions_, we can call this function as well to set this up:
```r
use_github_actions()
```
* let's re-build the package now. (look for rstudio button `install` in `build` tab)
---
## Adding a **Vignette**
* Vignette's are a great feature of R packages. They are full text introductions of the package to a first time user.
* A _tutorial_ for your package.
* This is going to be much more verbose and spiked with example input and ouput than the standard documentation.
* Often it features the main use case of your package.
* There is an [entire chapter](https://r-pkgs.org/vignettes.html) on `r-pkgs` dedicated to this!
### Adding the Vignette(s)
```r
usethis::use_vignette("vignette-toypackage-1")
```
---
## Deploy package documention on a website
<br>
<br>
* 🚨 Now we are entering the seriously cool zone of R package development 😎
* Wouldn't it be 🤩 amazing if all of our package documentation, the content of our readme, and any explanatory articles we might have written as vignettes, were **available on a (free to host!) website which is always up to date**?
---
## You Bet It's Cool 😎 {transition="zoom" transition-speed="slow"}
<!-- ## Deploy package documention on a website 2{background-image="https://media.giphy.com/media/8q92vsFOM9I2s/giphy-downsized-large.gif" background-position="50% 75%" background-size="40% auto"} -->
<!-- * 🚨 Now we are entering the seriously cool zone of R package development 😎 -->
<!-- * Wouldn't it be 🤩 amazing if all of our package documentation, the content of our readme, and any explanatory articles we might have written as vignettes, were **available on a (free to host!) website which is always up to date**? -->
![](https://media.giphy.com/media/8q92vsFOM9I2s/giphy-downsized-large.gif)
---
## Deploy package documention on a website 3
* Ready?
. . .
```r
usethis::use_pkgdown()
```
* `pkgdown` is a package for website and docs building.
. . .
* Let's build that site!
```r
pkdown::build_site()
```
. . .
* Let's get `gh-actions` going
```r
usethis::use_pkgdown_github_pages()
```
* commit everything and push to github!
---
## Summary
::: {.callout-tip}
# Key Points
1. `RStudio` greatly facilitates `R` package development.
2. `R` packages contain code, data and documentation in highly structured fashion.
3. We are encouraged to run automated unit tests.
3. It is relatively straightforward to publish the package to github for collaboration.
4. It is equally straightforward to build and publish a full website with package documentation and vignettes, hosted _for free_ on github.com.
:::