How to install and load packages in R

R packages contain functions, compiled code and often example datasets. To install a package you use the install.packages() function, for example if you want to install a package called ggplot2 you would type the following into the console panel:

install.packages("ggplot2")

Press ENTER and wait as the package downloads, you can watch the progress as it is printed out in the console.

Once installed, to use the functions that come with a package you need to specify the library.

The reason for this is that after installation the R packages are stored under a directory called “library” in the R environment.

For example to use the ggplot2 package in your R script, you would type the following at the top of the R script:

library("ggplot2")

Like this:

Note that not all packages will be compatible with your R version, it is a good idea to check first by going to the cran page, for example with ggplot2:

https://cran.r-project.org/web/packages/ggplot2/index.html

The red arrow here highlights where the compatible R versions are specified.