install.packages("dplyr")
## Downloads once to your machine (adds dplyr to your library).
## Notice the quotation marks around the package name.4 Install and Load Packages
How to set up your install.R file and load libraries
This chapter introduces R packages and libraries, why they matter for reproducible public health research, and how to install, load, and organize them in your own projects. Students will learn the difference between installing a package (once per computer) and loading a package (every session), how to keep all installations in one install.R file organized by the steps of the data science workflow, how to load libraries at the top of a Quarto report, and how to clearly comment their code so students and readers can understand what each package is doing in the context of a public health research project.
package, library, install.R
- ModernDive 1.3: What are R packages? (the best beginner explanation of packages)
- R4DS: The tidyverse (how to install and load the tidyverse)
- tidyverse packages (which packages
library(tidyverse)loads, and which it does not)
- Install once.
install.packages("name")downloads a package to your computer. You only do this one time per computer. - Load every time.
library(name)turns the package on for your current R session. You do this every time you open RStudio, at the top of every script and report.
4.1 Introduction to Libraries and Packages
Think of R as a new phone. A new phone can already do the basics: make calls, take photos, and send texts. R is the same. As soon as you install it, R can already do a lot, such as basic math, simple plots, and statistical tests like t.test().
A package is like an app. An app adds something your phone could not do before, and someone else built it and shared it in an app store. In the same way, a package is a bundle of functions, help files, and sometimes data that extends what R can do. Packages are written and shared by the R community, which is why there are thousands available in R’s “app store”, which is called CRAN. (This way of explaining packages comes from ModernDive.)
Your phone also teaches you the two steps for using a package.
- You download an app once. After that, it stays on your phone.
install.packages("dplyr")downloads thedplyrpackage to your computer, and it stays there. The place on your computer where your installed packages are kept is called your library, like the home screen that holds all of your apps. - You open an app every time you want to use it. A maps app does nothing until you tap it.
library(dplyr)opens thedplyrpackage from your library so that you can use its functions in your current R session. When you close RStudio, every package closes, so you open the ones you need again the next time, at the top of your report.
You do not need every app in the app store, and you do not need to learn every package. This playbook gives you the plays (code) to copy, and each chapter tells you which packages its plays need. Your job is to make sure those packages are installed once and loaded at the top of your report.
How to Write the Code
library(dplyr)
## Loads dplyr for this R session so you can use verbs like filter() and summarise()
## No quotation marks are needed.4.2 Packages Used in This Playbook
You do not need a long list of packages. The packages below are the ones that the plays in this playbook actually use. Base R also comes with built-in packages (e.g., stats, utils) that are already installed, so you never need install.packages() for them.
Core packages (everyone installs these)
| Step | Package | What you use it for | Chapters that use it |
|---|---|---|---|
| Import | readxl | read_excel() to import your .xlsx survey data |
Import Data Once, Start a Report, Combine Datasets, Creating Composites |
| Import | haven | read_sav() to import SPSS .sav files |
Import Data Once, Mutate Variables, Compare 1 Group, Pre/Post |
| Tidy | tidyr* | pivot_longer() and pivot_wider() to reshape long ↔︎ wide data |
Format Data in tidyr, Compare 1 Group, Pre/Post |
| Tidy | naniar | replace_with_na_all() to turn codes like -99 into missing values |
Mutate Variables, Compare 1 Group, Pre/Post |
| Transform | dplyr* | select(), filter(), mutate(), and joins |
almost every chapter |
| Transform | psych | scoreItems() and alpha() for composites and reliability; describe() for descriptive statistics |
Creating Composites, Methods & Results |
| Visualize | ggplot2* | all plots | Build a Plot in Layers, Visualize a Comparison, Visualize a Relationship, Compare 1 Group, Pre/Post |
| Model | stats (base) | t.test(), kruskal.test(), cor.test(), lm() |
comes with R: nothing to install or load |
| Communicate | knitr | kable() for tables in your report |
Mutate Variables, Creating Composites, Methods & Results |
| Communicate | rmarkdown | lets RStudio render a .qmd report that contains R code |
every report |
*installed and loaded all at once with the tidyverse
Extra packages (install only if you use that chapter)
| Package | What you use it for | Chapter that uses it |
|---|---|---|
| see, gghalves, ggdist | half-violin and raincloud plots | Compare 1 Group, Pre/Post |
| english | write numbers as words (e.g., “twelve”) | Methods & Results (advanced) |
The advanced chapters Import Data Live (httr, jsonlite, readr) and Methods & Results (scales, stringr, tibble) use a few more packages, but these are all installed automatically with the tidyverse, so there is nothing extra to install.
When a new chapter needs a package that is not on this list, the chapter will tell you, and you can add one line to your install.R file.
install.packages("tidyverse") installs many of these packages at once, including readxl, haven, tidyr, dplyr, and ggplot2. library(tidyverse) loads the core ones (such as ggplot2, dplyr, tidyr, readr, and stringr), but it does not load readxl or haven. You still need library(readxl) to import Excel files and library(haven) to import SPSS files.
4.3 Creating install.R file
This document will install all your packages before you begin your coding in an organized manner.
Note: It is helpful to comment on your install.R the “step” of the process the package is for and what purpose your package serves. As you finish your coding, you might realize certain packages are not necessary. That’s why it is useful to understand the specific role each package plays in your script.
flowchart LR
A["<b>IMPORT</b><br/>readxl<br/>haven"] --> B["<b>TIDY</b><br/>tidyr<br/>naniar"]
B --> C["<b>TRANSFORM</b><br/>dplyr<br/>psych"]
C --> D["<b>VISUALIZE</b><br/>ggplot2"]
D --> E["<b>MODEL</b><br/>stats (comes with R)"]
E --> F["<b>COMMUNICATE</b><br/>knitr<br/>rmarkdown"]Example install.R file
In your RStudio Project, create a new file that is “R Script” and title it install.R. Run the whole file one time by clicking the “Source” button. It may take several minutes. You do not need to run it again unless you get a new computer or need a new package.
## install.R
## Run this file ONE time on your computer.
## comments indicate what each package is used for
## IMPORT
install.packages("readxl") # read in xlsx files with read_excel()
install.packages("haven") # read in SPSS .sav files with read_sav()
## TIDY
install.packages("tidyverse") # consistent “tidy” toolkit (includes tidyr, dplyr, ggplot2, readr, stringr, etc.)
install.packages("naniar") # replace codes like -99 with missing values (NA)
## TRANSFORM
# install.packages("tidyverse") ## (already installed above) dplyr: select, filter, mutate, join
install.packages("psych") ## composite/scale scores, cronbach's alpha, descriptive stats
## VISUALIZE
# install.packages("tidyverse") ## (already installed above) ggplot2: all graphs and figures
## MODEL
# stats comes with R: t-tests, kruskal-wallis, correlations, and regression need no installation
## COMMUNICATE
install.packages("knitr") ## tables with kable() in Quarto reports
install.packages("rmarkdown") ## needed for RStudio to render Quarto reports with R code
## EXTRAS: remove the # only if you use that chapter
# install.packages("see") ## half-violin plots (Compare 1 Group, Pre/Post)
# install.packages("gghalves") ## half-violin plots (Compare 1 Group, Pre/Post)
# install.packages("ggdist") ## raincloud plots (Compare 1 Group, Pre/Post)
# install.packages("english") ## write numbers as words (Methods & Results)Note: See the tidyverse lines under TRANSFORM and VISUALIZE. You do not need to install packages twice. You can comment out the line of code but still note the purpose it serves.
install.packages() in your report
Keep install.packages() in your install.R file (or type it in the console). Do not put it inside a code chunk in a .qmd report. Otherwise, R will try to download the package every time you render, which is slow and often causes the render to fail.
4.4 Loading libraries in your report
Every Quarto report (.qmd) should start with one code chunk that loads the packages the report uses. Use the same workflow order and comments as your install.R file. Only load what you actually use.
## IMPORT
library(readxl) # read in xlsx files
## TIDY + TRANSFORM + VISUALIZE
library(tidyverse) # loads tidyr, dplyr, ggplot2, and more
library(naniar) # replace -99 with NA
library(psych) # composite scores, reliability, and descriptive stats
## COMMUNICATE
library(knitr) # tablesWhen you render a report, R starts a fresh session. This means the packages you loaded by hand in the console do not count: if the library() line is not in the report, the render will fail even though your code worked in the console.
4.5 Common Errors
there is no package called ‘psych’→ The package is not installed on your computer. Runinstall.packages("psych")once in the console (or add it toinstall.R), then runlibrary(psych)again.could not find function "read_excel"→ The package is installed but not loaded. Run thelibrary()line for the package that function comes from (here,library(readxl)), and make sure that line is in your load-library chunk.package ‘stats’ is a base package, and should not be updated→ You tried to install a package that already comes with R. Delete thatinstall.packages()line; nothing else is needed.- R asks “Do you want to install from sources the package which needs compilation?” → Type
noand press enter. You will get the ready-made version, which is all you need.