Style guide ๐Ÿง‘๐Ÿปโ€๐Ÿ’ป

Modified

July 23, 2023

R style guide โœ…

The tidyverse style guide

pipes โ€” |> ยท ๐ŸŒฌ๏ธ

  • one line for each step in a pipe
  • first line pipe with name of new object and assignment operator (only)
  • use Base-R pipe |> over Tidyverse-R pipe %>% for R >= 4.2
    • placeholder _ (|>) instead of . (%>%)
    • check Use native pipe operator in RStudio

data ยท ๐Ÿ”ข

  • use coherent prefixes for groups of data // dt dt_ctry dt_ctz
  • prefix raw_ for raw data read into object with

plots ยท ๐Ÿ“Š

  • prefix pl for plot objects // pl pl1 pl2
  • data for plot only into pl_dt object

models ยท ๐Ÿ”ฌ

  • prefix mo for model objects // mo mo_lm mo1

workflow ยท โš™๏ธ

  • .gitignore sources with source__ prefix
    • [ single option to ignore copyright protected, personal or sensible sources ]
  • final checks
    • restart R session and run all
    • check all object names
    • check console messages and warnings
  • reproducible environments with Rocker

packages ยท ๐Ÿ“ฆ // see snippet below

  • use conflicted to avoid function name conflicts
    • load first with library(conflicted)
    • specify preferred functions (e.g. conflicts_prefer(dplyr::filter()))
  • load library(tidyverse) after conflicted
  • add brief description why package is loaded
    • library(broom) # models // tidy results
  • order packages loaded by thematic groups
    • plot โ€” patchwork ggrepel
    • models โ€” broom ยท ggeffects
  • specify single usage of package with ::
    • comment below loading packages block // # janitor::
    • no comment for usage tidyverse of packages that are not loaded with library(tidyverse) (e.g. glue readxl)
    • [ reduce potential name conflicts and code completion options ]

Snippets ยท โœ‚๏ธ

Loading packages

library(conflicted) # create errors for function name conflicts
conflicts_prefer(dplyr::filter, .quiet = TRUE)

library(tidyverse)

# order alphabetically in section and provide category with brief description
library(broom)      # models // tidy results
library(ggeffects)  # models // visualize model effects
library(patchwork)  # plots  // arrange plots
library(reactable)  # layout // interactive data tables
library(sf)         # maps   // spatial data tools

# DT:: skimr:: viridis::

Note โ€” These are my personal best practices for code formatting in Tidyverse R. They have evolved over time and not all my previous code may follow these guidelines.