Install a Package
In this tutorial, we will walk you through installing the
ggplot2 packages for
At the end of this activity, you will:
- Know how to install an
- Be able to explain what a package is in
What is a Package?
A package, in
R is a bundle of pre-built functionality. Think of it like a toolbox. Except for the tools may do things like calculate a mathematical function e.g.
sum or create a plot.
Install a Package
R we install packages using the
install.packages("packageNameHere") function. Let’s get
R Markdown and
knitr installed so we can use them in our exercises. In the
R console within
R Studio, use the code below to install packages individually.
# install knitr install.packages("knitr") # install the rmarkdown package install.packages("rmarkdown") # install ggplot for plotting install.packages("ggplot2") # install dplyr for data manipulation install.packages("dplyr")
Data tip You can install as many packages as you want in one string of code as follows
Call Package in R
Once the package is installed, to use it, you call the package at the top of your script like this:
# load libraries library(knitr) library(rmarkdown) library(ggplot2)
Note that you don’t need to use quotes around the package name when you call it using the
library() function. But you do need the quotes when you install a package.
In our case, the
R Markdown packages load buttons and options within the
R Studio environment that we can use. Thus we won’t have to call these two packages in our code in this lesson. However, when we use
ggplot2 to plot, we will have to call it. We will see how calling a package works in a later set of lessons.
What Does Loading a Library Do?
When you load a library in
R, you are telling
R to make all of the FUNCTIONS available in the package (think of functions like tools that perform tasks - for example
plot()) available to you in your code.
Where Do R Packages Live?
R packages are most often found on the CRAN repository. When you call
install.packages("package-name-here") you are actually downloading the packages from CRAN. However there are other places where you may install packages from including:
- and more
Data tip While some
R packages are just fine to use. Keep in mind that not all
R packages are secure. Learn more.
Advanced - Install Multiple Packages at Once
You can also install multiple
R packages at the same time. To do that, you send the
install.packages() function a vector or list of package names.
A vector is a list of objects. the syntax for a vector is:
you can also store numbers in a vector.
c(1, 5, 74)
So if we want to install
dplyr all at once, we do this:
# install several packages at once install.packages(c("rmarkdown", "ggplot2", "dplyr"))