Packages (optional)
Optional. You don’t need this before Week 1. Come back to it for a head start on later weeks, or as a refresher.
Packages
R comes with many functions built in; together these are called “base R”. Packages add more. From Week 2 we use two of them, {ggplot2} and {dplyr}.
Using a package takes two steps, which match Python’s pip install and import:
- Install it, once per computer:
install.packages("ggplot2"). - Load it, once per R session:
library("ggplot2").
If you call a function from a package you have not loaded, R stops with an error like could not find function "ggplot". The same error appears if you mistype a function’s name, so check both.
On this site, and on the course’s exercise pages, R runs in your browser and the packages each page needs are installed for you. On your own computer, you install them yourself.
A common error
Load a package
In the code chunk below, load the {tidyverse} package. Whenever you load a package R will also load all of the packages that the first package depends on. {tidyverse} takes advantage of this to create a shortcut for loading several common packages at once. Whenever you load {tidyverse}, {tidyverse} also loads {ggplot2}, {dplyr}, {tibble}, {tidyr}, {readr}, {purrr}, {forcats}, {stringr}, and {lubridate}.
library("tidyverse")Good job! R will keep the packages loaded until you close your R session. When you re-open R, you’ll need to reload your packages.
Quotes
Did you know library() is a special function in R? You can pass library() a package name in quotes, like library("tidyverse"), or not in quotes, like library("tidyverse")—both will work! That’s often not the case with R functions.
In general, you should always use quotes unless you are writing the name of something that is already loaded into R’s memory, like a function, vector, or data frame.
Install packages
But what if the package that you want to load is not installed on your computer? How would you install the {dplyr} package on your own computer?
install.packages("dplyr")Good job! You only need to install a package once, unless you wish to update your local copying by reinstalling the package. Notice that install.packages() always requires quotes around the package name.
Congratulations!
Congratulations. You now have a formal sense for how the basics of R work. Although you may think of your self as a data scientist, this brief computer science background will help you as you analyze data. Whenever R does something unexpected, you can apply your knowledge of how R works to figure out what went wrong.