Style Guide

Code style

  • In general, follow the conventions of the tidyverse style guide.
  • Prefer packages to be explicitly namespaced with a double colon in production code, like dplyr::mutate(), though this is not essential in exploratory data analysis.
  • Favour the base R pipe (|>) over the {magrittr} pipe (%>%).
  • Avoid library(tidyverse) in production code because it attaches a lot of packages that might not be used, though you may use it in exploratory data analysis.
  • Use {styler} and {lintr} (or Python equivalents such as black) to tidy your code.
  • Insert linebreaks in your code at or before column 80.
  • When using {dplyr}, favour one mutate over many. For example, between the two examples below, example B is preferred:

EXAMPLE A:

library(dplyr)

starwars |>
  mutate(height_cm = height) |>
  mutate(name_copy = name)

EXAMPLE B:

dplyr::starwars |>
  dplyr::mutate(
    height_cm = height,
    name_copy = name
  )

Line endings

To avoid excessive whitespace cluttering up Git diffs, set your chosen IDE to use LF line endings.

For RStudio, select Tools > Global Options > Code > Saving. Under Serialization, set the Line ending conversion to Posix (LF).

Screenshot showing how to set line endings correctly in RStudio

For VSCode, follow the instructions here.

You should also change your git settings to checkout in LF by running this in your terminal: git config --global core.autocrlf false

Per repository, you can run git add --renormalize . to fix line endings.

Additional assorted notes on style 😎

  • Our preferred date format is ISO: YYYY-MM-DD
  • Favour Quarto (.qmd files) over R Markdown (.Rmd) for document production.
  • Use Git for all projects and GitHub as the remote home for of all of the project code.
  • Use the Reproducible Analytical Pipelines (RAP) approach wherever possible.
  • Line breaks in Markdown (.md) files should be at 120 characters or at sentence breaks.
  • When writing about code, use curly braces to identify a {package} name and use backticks around `functions()` as these render nicely and highlight the words clearly.
  • If you’re not sure about something try the NHS-R Way, the UK Government accessibility guidelines, or the Turing Way. If you’re still not sure, just ask the team.