ETC5523: Communicating with Data

Tutorial 9

Author

Michael Lydeamore

Published

September 1, 2001

🎯 Objectives

  • practice writing long-form documentation vignettes
  • write functions and its documentation using usethis and roxygen2
  • convert your package documentation into a website with pkgdown
  • write a new R function for your package and test it with testthat
  1. install.packages(c("pkgdown", "testthat"))

  2. This tutorial extends the package we built together in tutorial 8.

If you would like to start from a clean slate, you can clone the github repo below:

git clone https://github.com/etc5523-2022/cwdata.git

Exercise 9A

Open the cwdata project directory and create a new vignette via usethis.

The name of the vignette should be “crops” and the title will be “Our World in Data: Key Crop Yields”.

Your vignette should contain the following:

  • A description of the data, including it’s source, and how to access it with your package.
  • Two ggplot2 visualisations with short descriptions, giving examples of things you could learn from the key_crop_yields data. If you are stuck on ideas take a look at the charts found on the Our World in Data website. Remember that any external packages you use should be added to your DESCRIPTION file under Suggests.

Once you have finished your vignette, create a README file via usethis that describes the intent of the package and how you could install it from your github.

Exercise 9B

Build a local pkgdown website. Modify the pkgdown YAML file so your website has the following:

  • a customised theme for the website
  • the vignette is available via “Articles” link in the navbar

Exercise 9C

Now let’s create a function to help us create a “proportional stacked area chart”.

The function will take a vector of numbers and convert them to proportions. Missing values should be removed from the input vector but remain in the output vector.

Here’s some examples of what the output should look like:

x <- c(10, 30, 40)
stack_normalize(x)
# c(0.125, 0.375, .5)
x <- c(75, 0, 5, 20, NA)
stack_normalise(x)
# c(0.75, 0, 0.05, 0.2, NA)
x <- c(NA, NA, 10)
stack_normalize(x)
# c(NA, NA, 1)

Create a new R script in your package called stack-normalise.R and place the function. Remember to document it and provide examples of use.

Exercise 9D

Set up testthat for use with your package. Create a new file that will contain tests for stack_normalise via usethis.

Write some tests to verify that your function works correctly, you can use the examples above to help you get started.

Remember that the function should:

  • always return a vector of numbers between 0 and 1
  • unless there are NAs in which case it should preserve those