Chapter 11 Packages

The majority of functions in R come in packages. These are essentially folders that contain all the code that gets run whenever you use a function along with help files and some other data. Basic R installation comes with several packages and every time you open R or RStudio, some of these will get loaded, making the functions these packages contain available for you to use.

Other functions however come in packages that either don’t get loaded automatically upon startup or need to be installed. For instance, a very handy package for descriptive statistics is psych, and for data visualisation ggplot2. If we want to make use of the many functions in this packages, we need to first install them using the install.packages() command:

install.packages("psych")
install.packages("ggplot2")

You only ever need to install a package once. R will go online, download the package from the package repository and install it on your computer. Once we’ve installed a package, we need to load it so that R can access the functions provided in the package. This is done using the library() command:

library(psych) # no quotes this time
library(ggplot2)
## 
## Attaching package: 'ggplot2'
## The following objects are masked from 'package:psych':
## 
##     %+%, alpha

Packages have to be loaded every session. If you load a package, you can use its functions until you close R. When you re-open it, you will have to load the package again. For that reason, it is very useful to load all the packages you will need for your data processing, visualisation, and analysis at the very beginning of your script. If you’re not sure what you have loaded, you can check the Packages list on the bottom right-hand side of your RStudio window.