5. Packages

In this section we’ll highlight the use of packages. These packages provide you with the necessary building blocks for doing all kinds of computations and analyses in R.

Section structure:


5.1. What is the purpose of packages?

You already have experience with some of the functionality that come standard with the (basic) R installation. For instance, you have seen that the functions hist() and weighted.mean() are directly available after installation. For many other functions, however, you’ll need to install (at least one) package to use the function.

At the time of the development of this tutorial there were already over 11,000(!!) packages available from the largest data base for R packages, CRAN (short for Comprehensive R Archive Network). Often, these packages contain functions that are focused on a similar topic (such as data visualization or certain types of analyses). A list of all these packages is found here.


5.2. Installing and using packages

The video below shows the steps you need to take to be able to install and use packages.



To replicate the steps in this video, type and run:

weight <- c(80, 40, 50, 80, 90, 60, 75, 85, 66, 105)
length <- c(1.75, 1.6, 1.55, 1.68, 1.8, 1.9, 1.75, 1.85, 1.66, 1.8)
BMI <- weight / (length^2)

install.packages('rgl')  #install package rgl, replace rgl with a package of your choice to install that package
library(rgl)  #load package rgl from the system library, replace rgl with a package of your choice to load that package
?plot3d
plot3d(x = weight, y = length, z = BMI, col = 'red')


An alternative to install packages is via the bottom right panel, Packages -> Install:



You can also use this panel to load the packages that are available in the System Library by clicking the box in front of their name.


5.3. A note of warning

Obviously, the large data base of packages makes R very attractive to use for various specialized computing and analyses tasks. You might now wonder: where do all these packages come from? The answer is simple: packages can come from anybody! Anybody (with at least some experience with R) can develop an R-package and make it available via CRAN. This page tells you exactly which steps you need to take to make your own R package.

Like R (and this tutorial), packages come with absolutely no warranty. Hence, you need to be careful when you use an unfamiliar R-package with an unfamiliar developer! You may want to ask your colleagues and search the web to check for experiences with the package or you may even want to contact the developer. Whatever you do: be critical when using unfamiliar packages!

In addition: packages (like R itself) are regularly updated. Therefore, it is advisable to include version numbers of any packages you use as a comment in your script to enable you (or others) to replicate the analysis later on.