-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.Rmd
1025 lines (672 loc) · 19.4 KB
/
index.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
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: "<br />Building an R package"
subtitle: "<i>Become an R developer</i>"
date: .inst[November 2023]
author: <br /><br /><br />Nicolas Casajus & Aurélie Siberchicot
output:
xaringan::moon_reader:
css: ["css/xaringan-themer.css", "css/custom.css"]
lib_dir: "libs"
seal: true
yolo: false
self_contained: false
nature:
ratio: "4:3"
titleSlideClass: ["right", "middle"]
highlightStyle: 'zenburn'
highlightLines: false
countIncrementalSlides: false
slideNumberFormat: "%current% / %total%"
beforeInit: "libs/macros.js"
---
## What's an R Package?
--
`r fontawesome::fa_i("quote-left")`
In `r fontawesome::fa_i("r-project")`, the fundamental unit of shareable code is
the package.
A package bundles together `code`, `data`, `documentation`, and `tests`,
and is easy to share with others.
.right[— **_Hadley Wickham_**]
```{r include=FALSE}
r = getOption("repos")
r["CRAN"] = "http://cran.us.r-project.org"
options(repos = r)
library(magrittr)
```
--
<br />
An `r fontawesome::fa_i("r-project")` package:
- is a collection of `well-documented functions`
- makes your work more `reproducible`
- makes your code `useful` for you and for others
--
<br />
As of today (`r Sys.Date()`):
- **`r nrow(available.packages())`** packages are available on the [`CRAN`](https://cran.r-project.org)
- **`r 'https://www.bioconductor.org/packages/release/bioc/' %>% rvest::read_html() %>% rvest::html_table() %>%.[[1]] %>% nrow()`** packages on `Bioconductor`
---
## Must-read resources
<br />
.center[
[![:scale 36%](img/r-pkg.jpg)](https://r-pkgs.org/)
[![:scale 34%](img/r-ext.png)](https://cran.r-project.org/doc/manuals/r-release/R-exts.html)
]
---
## Recommended environment
<br />
.center[
![:scale 40%](img/rstudio.png)
]
.center[
![:scale 13.0%](img/hex-devtools.png)
![:scale 13.0%](img/hex-usethis.png)
![:scale 13.0%](img/hex-roxygen2.png)
![:scale 13.0%](img/hex-rmarkdown.png)
![:scale 13.0%](img/hex-testthat.png)
]
.center[
![:scale 28.0%](img/up-to-date.png)
]
---
## Development workflow
<br />
![:scale 100.0%](img/pkg-steps.png)
---
## Creating the structure
<br />
![:scale 100.0%](img/pkg-step-1.png)
---
## Creating the structure
<!-- - Using **RStudio** -->
![:scale 10%](img/rstudio.png)
.center[
![:scale 32%](img/new-1.png)
![:scale 32%](img/new-2.png)
![:scale 32%](img/new-3.png)
]
`r fontawesome::fa_i("hand-point-right")` Make sure to select `Create R Package using devtools`
`r fontawesome::fa_i("hand-point-right")` A **package name**
can only contain `letters`, `numbers`, and the `.`
`r fontawesome::fa_i("hand-point-right")` Check that the chosen name is not already in use with `available::available()`
--
<br />
```{r echo = TRUE, eval = FALSE}
## Alternatively ----
usethis::create_package("/absolute/path/to/the/package/name")
```
---
## Package structure
```
.
├── (.git) # Git files system
├── (.gitignore) # Untracked files by git
│
├── (mypkg.Rproj) # RStudio files
│
├── .Rbuildignore # List of non-standard package files
│
├── R/ # Folder to store (only) R functions
│ ├── myfun-1.R # A first R function
│ └── myfun-2.R # A second R function
│
├── man/ # R functions documentation folder (automatically edited)
│ ├── my_fun_1.Rd
│ └── my_fun_2.Rd
│
├── DESCRIPTION # Package metadata
│
└── NAMESPACE # Automatically edited
```
---
## Writing an R function
<br />
![:scale 100.0%](img/pkg-step-2.png)
---
## Writing an R function
`r fontawesome::fa_i("hand-point-right")`
Let's create a first function `moyenne()`.
--
<br />
- First, we will create a new `r fontawesome::fa_i("r-project")` file in the folder **R/**.
```{r, echo = TRUE, eval = FALSE}
usethis::use_r("moyenne")
```
--
<br />
- Now we can implement our function `moyenne()`.
```{r, echo = TRUE, eval = FALSE}
moyenne <- function(x) sum(x) / length(x)
```
`r fontawesome::fa_i("hand-point-right")`
Resources: [`Tidyverse style guide`](https://style.tidyverse.org/)
---
## Time to document
<br />
![:scale 100.0%](img/pkg-step-3.png)
---
## Time to document
.pull-leftt[
.center[[![:scale 75%](img/hex-roxygen2.png)](https://cran.r-project.org/web/packages/roxygen2/vignettes/roxygen2.html)]
]
.pull-rightt[
- Specially-structured comments **preceding** each function definition
- Lightweight syntax easy to write and to read
- Syntax: `#' @field value`
- Keep function definition and documentation in the same file
- Automatically write `.Rd` files and **NAMESPACE**
]
--
Each `roxygen` header will always start with these two fields:
```{r, echo = TRUE, eval = FALSE}
#' @title Short title of the function (one line)
#'
#' @description A longer description of what the function does (several lines)
```
--
`r fontawesome::fa_i("hand-point-right")`
Keywords `@title` and `@description` can be omitted.
```{r, echo = TRUE, eval = FALSE}
#' Short title of the function (one line)
#'
#' A longer description of what the function does (several lines)
```
---
## Time to document
`r fontawesome::fa_i("hand-point-right")`
If your function has `input parameters`, each one must be documented.
```{r, echo = TRUE, eval = FALSE}
#' @param param_1 description
#' @param param_2 description
```
--
In our function `moyenne()`:
```{r, echo = TRUE, eval = FALSE}
#' @param x a numeric vector
```
--
<br />
`r fontawesome::fa_i("hand-point-right")`
If your function `returns` an `r fontawesome::fa_i("r-project")` object,
use the keyword `@return`.
```{r, echo = TRUE, eval = FALSE}
#' @return What the function returns.
```
--
In our function `moyenne()`:
```{r, echo = TRUE, eval = FALSE}
#' @return A `numeric` representing the arithmetic mean of `x`.
```
--
If your function returns nothing, use the keyword `@return` as follow:
```{r, echo = TRUE, eval = FALSE}
#' @return No return value.
```
---
## Time to document
`r fontawesome::fa_i("hand-point-right")`
Add a section `@examples` to show how to use your function:
```{r, echo = TRUE, eval = FALSE}
#' @examples
#' x <- 1:10
#' moyenne(x)
```
--
<br />
If you don't want your example to be executed, use `\dontrun{}` when your example returns an error or does something that is dangerous
```{r, echo = TRUE, eval = FALSE}
#' @examples
#' \dontrun{
#' x <- 1:10
#' moyenne(x)
#' }
```
or `\donttest{}` when your example takes too long (for the CRAN standards).
```{r, echo = TRUE, eval = FALSE}
#' @examples
#' \donttest{
#' moyenne(runif(10e7))
#' }
```
---
## Time to document
`r fontawesome::fa_i("hand-point-right")`
Finally if you want your function to be used directly by user you need to add this tag.
```{r, echo = TRUE, eval = FALSE}
#' @export
```
---
## Time to document
Back to the R file of our function
```{r, echo = TRUE, eval = FALSE}
#' Compute the arithmetic mean
#'
#' This function computes the arithmetic mean of a numeric variable.
#'
#' @param x a numeric vector
#'
#' @return A `numeric` representing the arithmetic mean of `x`.
#'
#' @export
#'
#' @examples
#' x <- 1:10
#' moyenne(x)
moyenne <- function(x) sum(x) / length(x)
```
---
## Generating the documentation
`r fontawesome::fa_i("hand-point-right")`
It's time to generate the corresponding `.Rd` file from this `roxygen` header.
`r fontawesome::fa_i("hand-point-right")`
All `.Rd` files are stored in the `man` folder.
```{r echo = TRUE, eval = FALSE}
devtools::document()
```
```
✓ Writing 'man/moyenne.Rd'
✓ Writing 'NAMESPACE'
```
--
<br />
`r fontawesome::fa_i("hand-point-right")`
In addition to the creation of `man/moyenne.Rd` file, the `NAMESPACE` has been updated.
`r fontawesome::fa_i("hand-point-right")`
This file lists which functions need to be exported, i.e. directly
usable when loading the package (this file also deals with external dependencies).
```{r, eval = FALSE}
# Generated by roxygen2: do not edit by hand
export(moyenne)
```
---
## Testing the function
<br />
![:scale 100.0%](img/pkg-step-4.png)
---
## Testing the function
`r fontawesome::fa_i("hand-point-right")`
Before going any further, we have to try our function. So we will load our package
(and **NOT** sourcing the function).
```{r, echo = TRUE, eval = FALSE}
devtools::load_all()
```
--
<br />
Now we can use our function:
```{r, echo = TRUE, eval = FALSE}
moyenne(c(1, 2))
```
```
## [1] 1.5
```
--
<br />
What about `NA`?
```{r, echo = TRUE, eval = FALSE}
moyenne(c(1, 2, NA))
```
```
## [1] NA
```
***Hum...***
---
## Modifying the function
Our function does not seem to work properly.
`r fontawesome::fa_i("hand-point-right", class = "dark")`
We need to update the code to deal with `NA` values.
--
```{r, echo = TRUE, eval = FALSE}
moyenne <- function(x) {
x <- na.omit(x)
sum(x) / length(x)
}
```
--
<br />
Let's test the function again:
```{r, echo = TRUE, eval = FALSE}
## Reload the function ----
devtools::load_all()
## Testing the function ----
moyenne(c(1, 2))
## [1] 1.5
## Testing the function (with NA) ----
moyenne(c(1, 2, NA))
## [1] 1.5
```
---
## Modifying the function
That's better, but...
If user has `NA` values, this implementation will not inform him/her and will make the
decision to remove `NA`. Instead we are going to let user choose to delete the
`NA` or not.
--
<br />
`r fontawesome::fa_i("hand-point-right")`
Let's add an additional parameter to our function: `na_rm` with a default value
(`FALSE`). If `x` contains `NA` values and `na_rm = FALSE`, then an error will
be returned. If `na_rm = TRUE`, `NA` values will be removed and the
computation can be done.
--
```{r, echo = TRUE, eval = FALSE}
moyenne <- function(x, na_rm = FALSE) {
if (any(is.na(x))) {
if (na_rm) {
x <- na.omit(x)
} else {
stop("Argument 'x' contains NA values. Use 'na_rm = TRUE' to remove missing values.")
}
}
sum(x) / length(x)
}
```
---
## Modifying the function
Let's test the function again.
```{r, echo = TRUE, eval = FALSE}
## Reload the function ----
devtools::load_all()
## Testing the function ----
moyenne(x = c(1, 2))
## [1] 1.5
moyenne(x = c(1, 2, NA))
## Error in moyenne(x = c(1, 2, NA)):
## Argument 'x' contains NA values. Use 'na_rm = TRUE' to remove missing values.
moyenne(x = c(1, 2, NA), na_rm = TRUE)
## [1] 1.5
```
---
## Update documentation
<br />
![:scale 100.0%](img/pkg-step-3.png)
---
## Update documentation
```{r, echo = TRUE, eval = FALSE}
#' Compute the arithmetic mean
#'
#' This function computes the arithmetic mean of a numeric variable.
#'
#' @param x a numeric vector (can contain `NA` values).
#'
#' @param na_rm a logical value indicating whether `NA` values should be
#' stripped before the computation proceeds. Default is `FALSE`.
#'
#' @return A `numeric` representing the arithmetic mean of `x`.
#'
#' @details An error will be returned if `x` contains `NA` values and `na_rm`
#' is `FALSE` (default behaviour).
#'
#' @export
#'
#' @examples
#' moyenne(x = c(1, 2))
#'
#' \dontrun{
#' moyenne(x = c(1, 2, NA)) # error
#' }
#'
#' moyenne(x = c(1, 2, NA), na_rm = TRUE)
moyenne <- function(x, na_rm = FALSE) { ... }
```
And update the corresponding `.Rd` file and the `NAMESPACE`.
```{r echo = TRUE, eval = FALSE}
devtools::document()
```
---
## And so on...
<br />
![:scale 100.0%](img/pkg-step-5.png)
---
## Package metadata
Before we go any further, we need to edit some information about our package,
using the `DESCRIPTION` file:
- what defines our package (name, title, description, version, authors)?
- who can use our package and how (licence)?
- who should be contacted if there is a problem or question (the maintainer has the `cre` role)?
```{r, echo = TRUE, eval = FALSE}
usethis::edit_file("DESCRIPTION")
```
```
Package: mypkg
Title: A Minimal but Complete R Package
Version: 0.0.0.9000
Authors@R:
person(given = "Nicolas",
family = "Casajus",
role = c("aut", "cre", "cph"),
email = "nicolas.casajus@fondationbiodiversite.fr",
comment = c(ORCID = "0000-0002-5537-5294"))
Description: Illustrates the main structure and components of an R Package with
respect to the CRAN submission policies <https://cran.r-project.org/>.
License: GPL (>= 2)
Encoding: UTF-8
Roxygen: list(markdown = TRUE)
RoxygenNote: 7.1.2
```
`r fontawesome::fa_i("hand-point-right")`
Resources: [`DESCRIPTION file`](https://r-pkgs.org/description.html)
and [`Choose a license`](https://choosealicense.com)
---
## Check package
<br />
![:scale 100.0%](img/pkg-step-6.png)
---
## Check package
```{r, echo = TRUE, eval = FALSE}
devtools::check()
```
```
── R CMD check results ─────────────────────────────────── mypkg 0.0.0.9000 ───────
Duration: 11.6s
> checking R code for possible problems ... NOTE
moyenne: no visible global function definition for ‘na.omit’
Undefined global functions or variables:
na.omit
Consider adding
importFrom("stats", "na.omit")
to your NAMESPACE file.
0 errors ✓ | 0 warnings ✓ | 1 note x
```
--
<br />
`r fontawesome::fa_i("hand-point-right")`
**1 note**: Let's talk about package dependencies!
---
## Package dependencies
```
> checking R code for possible problems ... NOTE
moyenne: no visible global function definition for ‘na.omit’
Undefined global functions or variables:
na.omit
Consider adding
importFrom("stats", "na.omit")
to your NAMESPACE file.
```
<br />
`r fontawesome::fa_i("hand-point-right")`
So we need to import the function `na.omit()` from the package `{stats}`.
In `roxygen` header, import:
- either the whole package, with the tag `@import`:
```{r, echo = TRUE, eval = FALSE}
#' @import stats
```
- or only specific functions from a package, with the tag `@importFrom`:
```{r, echo = TRUE, eval = FALSE}
#' @importFrom stats na.omit
```
---
## Package dependencies
`r fontawesome::fa_i("hand-point-right")`
In your R code, call external functions with `::` for clarity and efficiency.<br />
Here `stats::na.omit()`
```{r, echo = TRUE, eval = FALSE}
moyenne <- function(x, na_rm = FALSE) {
if (any(is.na(x))) {
if (na_rm) {
x <- stats::na.omit(x)
} else {
stop("Argument 'x' contains NA values. Use 'na_rm = TRUE' to remove missing values.")
}
}
sum(x) / length(x)
}
```
---
## Package dependencies
`r fontawesome::fa_i("hand-point-right")`
**Do not forget** to update the `NAMESPACE` (and the `.Rd` files) with `devtools::document()`.
```
export(moyenne)
importFrom(stats,na.omit)
```
--
`r fontawesome::fa_i("hand-point-right")`
The `NAMESPACE` controls what happens when our package is loaded but
not when it's installed. This is the role of the `DESCRIPTION` file and we need to add
dependencies to this file.
---
## Package dependencies
`r fontawesome::fa_i("hand-point-right")`
Let's add the dependency `stats` in the `DESCRIPTION` file.
```{r, echo = TRUE, eval = FALSE}
usethis::use_package("stats", type = "Imports")
```
<br />
```
Package: mypkg
Title: A Minimal but Complete R Package
Version: 0.0.0.9000
Authors@R:
person(given = "Nicolas",
family = "Casajus",
role = c("aut", "cre", "cph"),
email = "nicolas.casajus@fondationbiodiversite.fr",
comment = c(ORCID = "0000-0002-5537-5294"))
Description: Illustrates the main structure and components of an R Package with
respect to the CRAN submission policies <https://cran.r-project.org/>.
License: GPL (>= 2)
Encoding: UTF-8
Roxygen: list(markdown = TRUE)
RoxygenNote: 7.1.2
Imports:
stats
```
---
## Dependencies types
- `Depends`: packages listed in this field are `installed` when your package is
installed and are `attached` when your package is attached.
**NEVER** use `Depends` and always use `Imports` (except for special cases).
--
- `Imports`: packages listed in this field are `installed` when your package is
installed but are `not attached` when your package is attached (there are just loaded).
**ALWAYS** use this method.
--
- `Suggests`: packages listed in this field are `not installed` when your
package is installed. Your package can use these packages, but doesn't require
them (e.g. to run tests, build vignettes, etc.).
--
<br/>
`r fontawesome::fa_i("hand-point-right", )`
Resources: Wickham & Bryan - R Packages
[**Chap 9**](https://r-pkgs.org/description.html),
[**Chap 10**](https://r-pkgs.org/dependencies-mindset-background.html) and
[**Chap 11**](https://r-pkgs.org/dependencies-in-practice.html)
---
## Check package
<br />
![:scale 100.0%](img/pkg-step-6.png)
---
## Check package
```{r, echo = TRUE, eval = FALSE}
devtools::check()
```
```
── R CMD check results ─────────────────────────────────── mypkg 0.0.0.9000 ───────
Duration: 11.6s
0 errors ✓ | 0 warnings ✓ | 0 notes ✓
```
---
## Install package
<br />
![:scale 100.0%](img/pkg-step-7.png)
---
## Install package
```{r, echo = TRUE, eval = FALSE}
## Install package ----
devtools::install()
```
--
<br />
`r fontawesome::fa_i("hand-point-right", )`
Now we can use our package.
```{r, echo = TRUE, eval = FALSE}
## Load and attach the package ----
library("mypkg")
## Use the package ----
moyenne(c(1, 2))
```
```{r, echo = TRUE, eval = FALSE}
## Use the package (without attaching it) ----
mypkg::moyenne(c(1, 2))
```
---
class: inverse, center, middle
## To go further...
---
## Advanced tests
- Testing is a vital part of package development
- But until now we just tried our code informally and on the fly
- Problem: it's time consuming, repetitive and it can break the code
`r fontawesome::fa_i("hand-point-right")`
Package `{testthat}`
.pull-leftt[
.center[[![:scale 75%](img/hex-testthat.png)](https://testthat.r-lib.org)]
]
.pull-rightt[
- Implements a lot of unit tests
- Formal automated testing
- Explicits how your code should behave
- Makes your code more robust
]
```{r, echo = TRUE, eval = FALSE}
usethis::use_testthat()
```
<br />
`r fontawesome::fa_i("hand-point-right")`
Resources:
[**R Packages Chap 13**](https://r-pkgs.org/testing-basics.html)
---
## Add a vignette
.pull-leftt[
.center[[![:scale 75%](img/hex-rmarkdown.png)](https://rmarkdown.rstudio.com/)]
]
.pull-rightt[
- A tutorial for your package
- Shows how to use your package
- Uses the syntax `Rmarkdown`
]
```{r, echo = TRUE, eval = FALSE}
usethis::use_vignette("mypkg")
```
<br />
`r fontawesome::fa_i("hand-point-right")`
Resources:
[**R Package Chap 17**](https://r-pkgs.org/vignettes.html)