R Markdown - Load all required packages once in a single chunk for use throughout the R Markdown document

Viewed 331

Is there a way in RMarkdown where I can load all packages that I need at once, without having to repeat them in every code chunk?

For example, this is what my code looks like

knitr::opts_chunk$set(warning = FALSE, message = FALSE) 

I. Data Import

Importing the csv file and understanding dataset dimensions.

library(readr)
df <- read_csv("df.csv")
dim(df)

II. Data Exploration

How many unique appointments exist in the dataset?

library(dplyr)
df %>%
  select(appointment_id) %>%
  distinct() %>%
  nrow()

How many of those appointments are part of a series?

library(dplyr)
df %>%
  select(appointment_id,appointment_set_id) %>%
  filter(!is.na(appointment_set_id)) %>%
  distinct() %>%
  nrow()

Notice that dplyr is repeated twice, and readr once. I'd like to know if all packages can be loaded at once in a single chunk and applied throughout the Markdown?

1 Answers

Yes, you can load all of your required packages at once in a single chunk, preferably at the beginning of the document, though it will work as long as it is attached before any chunk that uses any of the relevant packages' functions.
Packages can be loaded and attached in chunks, and they will remain so in your environment from that point on. An R Markdown does not necessarily create its own environment, so it generally works the same way as attaching a package in ordinary R use. This means that theoretically you don't need to have this loading chunk at all if you make sure you always manually load the relevant packages before you render.
The only potential issue here is if you run chunks out of order while working on the document, in which case it is possible that you run a chunk with a function from a package before running the loading chunk. This is relatively easily avoided and fixed. You can also theoretically attach your packages in the setup chunk, so it will always run first, if you are confident enough to mess with that stuff.

Related