What we will cover here is basically the tidyverse style guide. Here are some additional comments.
It is helpful to organize the content in your R script. Here are some recommendations.
Include meta-data about the R script including
# This script will perform ...
#
# Author: Jarad Niemi
# Written: 09 Apr 2023
# Modified: 10 Apr 2023 by Alex Wold
Include all packages necessary for the script as
library()
calls at the top of the script (after meta-data).
Generally put packages in decreasing order of important, i.e. most used
packages [in the script] go first and least used packages go last.
library("tidyverse"); theme_set(theme_bw())
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.2 ──
## ✔ ggplot2 3.4.0 ✔ purrr 0.3.4
## ✔ tibble 3.1.8 ✔ dplyr 1.0.10
## ✔ tidyr 1.2.1 ✔ stringr 1.4.1
## ✔ readr 2.1.2 ✔ forcats 0.5.2
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag() masks stats::lag()
library("Sleuth3")
library("ggResidpanel")
library("emmeans")
You may need to source other R scripts within your R script. This step, if needed, should be done right after loading packages.
source("01-read_data.R")
source("02-wrangle_data.R")
Only put necessary commands in the R script. If there are other steps
that you perform, e.g. summary()
of the data, leave these
out of the R script. You can, and should, run these interactively, but
they should not be included in the R script.
A good way to write R, a functional programming language, is to write functions for performing actions. Each function should be in its own R script whose name is the same as the function. These files can contain helper functions, but only if their sole purpose is for functions within this file.
For functions, utilize roxygen2 documentation.