+ - 0:00:00
Notes for current slide
Notes for next slide

Overview

  • GroundsWell Consortium
  • Motivation
  • Demo: Creating a custom R package
  • Beyond the basics
    • Tests
    • Vignettes
    • Documentation++
  • References
2 / 48

GroundsWell: Transforming our cities from the ground up

  • Establish important baseline health and environment factors

  • Layering co-produced existing data and interventions (e.g. to encourage use of local parks by people who do not ordinarily use them)

  • Assessing the impact on health and wellbeing (evidence)

GroundsWell Consortium

3 / 48

Motivation

4 / 48

What is a package?

A package bundles together code, data, documentation, and tests, and is easy to share with others [5]

5 / 48

What is a package?

A package bundles together code, data, documentation, and tests, and is easy to share with others [5]

For a very detailed overview of all the steps necessary to create your own packages, see this book:
https://r-pkgs.org

R packages book

5 / 48

Why should we build packages?

  • Reuse functions
  • Standardised documentation
  • Unit tests
  • Contribute to the scientific community

  • And of course, to create cool hex stickers and stick them on your work laptop.

Community-curated hex stickers

6 / 48

Where can I publish my work?

Firstly, you packages don't have to be public (i.e. you can create packages for internal use only).

install.packages("trainR")
7 / 48

Where can I publish my work?

Firstly, you packages don't have to be public (i.e. you can create packages for internal use only).

install.packages("trainR")
BiocManager::install("DESeq2")
7 / 48

Where can I publish my work?

Firstly, you packages don't have to be public (i.e. you can create packages for internal use only).

install.packages("trainR")
BiocManager::install("DESeq2")
  • GitHub (GitLab, Bitbucket, etc.): a more general software development and version control platform, https://github.com
remotes::install_github("villegar/trainR", "dev")
7 / 48

Can I get a DOI for my package?

Yes, of course. There are few websites where you can submit your work.

8 / 48

Can I get a DOI for my package?

Yes, of course. There are few websites where you can submit your work.

For example:

Villegas-Diaz, R., 2021. trainR: An Interface to the National Rail Enquiries Systems (0.0.1). Zenodo. https://doi.org/10.5281/zenodo.4506591

There are many more options, see this blog post [1].

For some tips on promoting your shiny new package, look here [3].

DOI: Digital Object Identifier

8 / 48

What do we need? (1)

Run the following lines inside RStudio:

install.packages("devtools")
install.packages("roxygen2")
install.packages("usethis")
install.packages("pkgdown")
install.packages("testthat")

9 / 48

What do we need? (2)

  • Patience (it gets tricky sometimes)
10 / 48

Demo: Creating a custom R package

(in less than 1000 steps)

12 / 48

Step-by-step (1)

  • Inside RStudio, navigate to

    File > New Project...

    The following window should be displayed:

13 / 48

Step-by-step (2)

  • Click on

    New Directory > R Package

    The following window should be displayed:

    Choose the name of your package (alphanumeric and underscore only), then click on Create Project.

14 / 48

Step-by-step (3)

15 / 48

Step-by-step (4)

RStudio should create the following files and directories for you (check the panel in the lower right corner, Files tab):

  • .gitignore: list of files to be ignored from version control.
  • .Rbuildignore: list of files to be ignored from the build of the package.
  • DESCRIPTION: this file contains metadata about your package (e.g. title, description, author(s), license, dependencies, etc.).
  • man [directory]: contains the documentation of your package.
  • NAMESPACE: auto-generated file listing functions, datasets and other objects in the package.
  • R [directory]: contains your R scripts
  • rthritis.Rproj: file with the details of your project (e.g. working directory, settings, etc.).
16 / 48

Step-by-step (5)

Before we carry on with the setup of our project, we should delete the existing man and R directories (we are not interested in the default functions created by RStudio).

Click on Yes:

17 / 48

Step-by-step (6)

I like to overwrite the template created by RStudio for the DESCRIPTION file, this can be done by executing the following line of code (in the Console tab, bottom left panel):

usethis::use_description()

You will be asked to acknowledge the changes, note that the option to overwrite is NOT always the first one (1), so make sure you pick the right number and hit Enter/Return.

18 / 48

Step-by-step (7)

Next, let's pick a license for our package. Chapter 13 of [5] covers in detail how to choose a license, I usually pick the MIT license (a very permissive one). To add your license, you can use the usethis package, choose the appropriate usethis::use_LICENSE_license function, where LICENSE should be replaced by your choice of license.

In my case, to use the MIT license:

usethis::use_mit_license(copyright_holder = "GroundsWell Consortium")

19 / 48

Step-by-step (8)

We need to update one more file, the NAMESPACE, so it lists all our new functions. We can do this by running the following command:

usethis::use_namespace()

20 / 48

Step-by-step (9)

One more file (I promise), now that we have updated few files, we can update the DESCRIPTION file and add our name, a title, a short description, etc.

Original:

Edited:

More details about the DESCRIPTION file can be found in Chapter 10 of [5].

Example of DESCRIPTION file for a package I published on the CRAN:
https://github.com/special-uor/fxTWAPLS/blob/master/DESCRIPTION

21 / 48

Step-by-step (10)

Let's create our first function (🎉), using the following command we can create new scripts inside the R directory:

usethis::use_r(name = "utils")

You can pick any name for your file, I have chosen utils as this will be my file with utilitarian functions.

Next, we can edit this file to create our first function (the file should be in your code Editor panel, left upper panel):

area_circle <- function(r) {
area <- pi * r ^ 2
message("The area of a circle with radius ", r, " is ", area)
return(area)
}
23 / 48

Step-by-step (11)

This function is still missing one of the key components of functions in a package, DOCUMENTATION.

To add the skeleton (template) documentation, place your cursor over the function name (anywhere), then click on Code > Insert Roxygen Skeleton:

If you are familiar with code documentation in R, you will recall that we use # before writing comments. Roxygen uses an additional character, ', to distinguish between regular comments and package documentation, # vs #'.

24 / 48

Step-by-step (12)

In addition to the special notation for the documentation, #', you might have noticed that the are some words with @ as prefix (e.g. @export), these are special fields to mark different sections of the documentation.

For this tutorial, we care about the following:

  • @param: used to describe the parameters of a function.
  • @return: used to describe the return object (if applicable) of the function.
  • @export: used to indicate that the function is "public", without it, the function will be available for "internal" use only.
  • @examples: used to add examples on how to use the function.

You can find more details here [7] and Chapter 17 of [5].

Roxygen2 - Documenting functions

25 / 48

Step-by-step (13)

Now, we can update the documentation. Roxygen uses the first line as the function title, then you can add a short description (leave a line between the title and description sections). Alternatively, you can use the @title and @description tags.

26 / 48

Step-by-step (14)

Before doing our first build, we need to generate the documentation, this can be done using the following command:

devtools::document()

27 / 48

Step-by-step (15)

Let's create our first build. Navigate to the Build tab (right upper panel), then click on

More > Build Source Package

28 / 48

Step-by-step (16)

Before installing our package, it's a good idea to check that its contents (documentation, examples, tests, etc.) are valid/correct. Navigate to the Build tab (right upper panel), then click on Check:

Notes are usually harmless, but you have to deal with them if you want to publish your package on the CRAN.

29 / 48

Step-by-step (17)

Finally, we can install and test our package. To install it, navigate to the Build tab (right upper panel), then click on Install:

30 / 48

Step-by-step (18)

Let's test our package. You can load the entire package to your R session with the library function and then execute the function you want:

library(rthritis)
area_circle(2)

Or, you can call the function directly using the PACKAGE::FUNCTION notation:

rthritis::area_circle(2)

Both, will result in the same output:

31 / 48

Step-by-step (19)

To checkout the documentation, you can run the following command:

?rthritis::area_circle

More generally, you can run ?PACKAGE::FUNCTION.

32 / 48

Step-by-step (20)

Generalising, you can run the following 3 lines of code, every time you want to document, check and install the latest version of your package:

devtools::document()
devtools::check()
devtools::install()
34 / 48

Beyond the basics

35 / 48

Tests

Testing your code can be painful and tedious, but it greatly increases the quality of your code. [4].

Implementing tests

We can start by running the following command in the Console tab (lower left panel):

usethis::use_test("utils")

You can choose any name you want for the test file, but it's a good practice to use the same name as the script that contains the functions you will be testing, here utils.

36 / 48

Tests (2)

You should see a new file called test-utils.R on the code editor:

We can ignore the example test and write our own tests, for example:

test_that("area_circle works", {
area <- area_circle(2)
expect_equal(area, pi * 2 ^ 2)
# test for invalid radius, a string
expect_error(area_circle("2"))
})

There are two tests here, one expecting to match expect_equal the output of the function. And another one, trying to "break" the function, by passing an invalid parameter to the function call, expect_error:

37 / 48

Tests (3)

To execute the tests you have created, you can navigate to the Build tab (right upper panel), then click on Test. Alternatively, you can run the following command in the Console tab (lower left panel):

devtools::test()

You should see something similar to the following output:

38 / 48

Tests (4)

For more details about unit tests in R, checkout the documentation for the testthat package: https://testthat.r-lib.org/articles/third-edition.html [4] and Chapter 14 of [5].

https://9gag.com/gag/ayMmqyb

https://9gag.com/gag/ayMmqyb

39 / 48

Vignettes (1)

A vignette is a long-form guide to your package ... perfect for showing a workflow that solves that particular problem, start to finish. [5]

Implementing vignettes

We can start by running the following command in the Console tab (lower left panel):

usethis::use_vignette("cfe_vs_rthritis", title = "Centre for Epidemiology Versus Arthritis")

You can choose any name you want for the vignette file, but I suggest a short version of the title.

40 / 48

Vignettes (2)

The new vignette file should automatically open on your code editor, then you can start editing and add all the relevant details (text, code, figures, etc.) to create an useful guide to your package.

More details about vignettes can be found in Chapter 18 of [5].

41 / 48

Documentation++ (1)

We previously documented a function, but we can also add more details about the package itself.

Once again, we can use usethis to create the necessary files:

usethis::use_package_doc()

This command will generate a new R script called {pkgname}-package.R. Next, we need to document, check and install the latest version of the package:

devtools::document()
devtools::check()
devtools::install()

Then, we can inspect the documentation for the package with the following command:

help(rthritis)
42 / 48

Documentation++ (2): README

It is a good practice to include a README file in your package. This file can be used to tell users where to get the package (including development versions), how to install it (this assumes the package is hosted somewhere online), provide details about citing the package, links to publications, etc.

To create a README file, run the following command:

usethis::use_readme_rmd()

Edit this file and add any relevant details about your package.

43 / 48

Documentation++ (3): Website

Using pkgdown, it is possible to generate a website with your package's documentation and vignettes, which can be a more user friendly way to share your work.

To set up the website, you can run the following command:

usethis::use_pkgdown()

To locally deploy the website for your package, you can run the following command:

pkgdown::build_site()
44 / 48

Documentation++ (4): Website

Find more details about pkgdown here [8] and Chapter 20 of [5].

45 / 48

Thank you!

r.villegas-diaz@liverpool.ac.uk

GitHub: https://github.com/villegar

Slides created using xaringan.

46 / 48

References (1)

[1] Dhanraj, N., 2020. How to publish R packages in good journals.
https://neerajdhanraj.medium.com/how-to-publish-r-packages-in-good-journals-55a3153bd409

[2] Moraga, P., 2022. Building R packages.
https://www.paulamoraga.com/blog/2022/04/12/2022-04-12-rpackages/

[3] Turner, H., 2020. Publishing and Promoting your R Package. https://www.heatherturner.net/talks/publishing-and-promoting-r-packages

[4] Wickham, H., 2011. testthat: Get Started with Testing. The R Journal, vol. 3, no. 1, pp. 5--10.

[5] Wickham, H. and Bryan, J., 2023. R packages (2e). https://r-pkgs.org

[6] Wickham, H., Bryan, J., Barrett, M., 2022. usethis: Automate Package and Project Setup. R package version 2.1.6, https://CRAN.R-project.org/package=usethis.

[7] Wickham, H., Danenberg P., Csárdi G., Eugster M., 2022. roxygen2: In-Line Documentation for R. R package version 7.2.3, https://CRAN.R-project.org/package=roxygen2.

47 / 48

References (2)

[8] Wickham, H., Hesselberth, J., Salmon, M., 2022. pkgdown: Make Static HTML Documentation for a Package. R package version 2.0.6, https://CRAN.R-project.org/package=pkgdown.

[9] Wickham, H., Hester, J., Chang, W., Bryan, J., 2022. devtools: Tools to Make Developing R Packages Easier. R package version 2.4.5, https://CRAN.R-project.org/package=devtools.

48 / 48

Overview

  • GroundsWell Consortium
  • Motivation
  • Demo: Creating a custom R package
  • Beyond the basics
    • Tests
    • Vignettes
    • Documentation++
  • References
2 / 48
Paused

Help

Keyboard shortcuts

, , Pg Up, k Go to previous slide
, , Pg Dn, Space, j Go to next slide
Home Go to first slide
End Go to last slide
Number + Return Go to specific slide
b / m / f Toggle blackout / mirrored / fullscreen mode
c Clone slideshow
p Toggle presenter mode
t Restart the presentation timer
?, h Toggle this help
Esc Back to slideshow