2.4 R Packages

R’s advanced functionality comes from the use of packages—user-defined programs (like apps on a phone)—that enable it to carry out particular tasks. We rely largely on a suite of packages called the tidyverse.

2.4.1 Installing packages

To install the tidyverse (or any package), use the command install.packages('packageName') in your script or console. Be sure to include the name of the package in quotes. Note that the tidyverse will take several minutes to install:


Just like installing an app on your phone, you only install a package once. After it downloads and unpacks, you never have to do it again.

2.4.2 Loading packages for use

You only have to install a package once, but you must load it in each R session to use it. Call the desired package using the command library(packagename). It’s a good idea to start any R script by loading frequently-used packages, especially tidyverse:

## -- Attaching packages -------------- tidyverse 1.3.0 --
## v ggplot2 3.3.3     v purrr   0.3.4
## v tibble  3.0.6     v dplyr   1.0.4
## v tidyr   1.1.2     v stringr 1.4.0
## v readr   1.4.0     v forcats 0.5.1
## -- Conflicts ----------------- tidyverse_conflicts() --
## x dplyr::filter() masks stats::filter()
## x dplyr::lag()    masks stats::lag()

Note that you can also call a specific function without loading the entire package that defines it. For example, haven::read_dta() executes the read_dta() function from the haven package without loading the package itself.