2  Pre-installing R packages for book

Author

Eliot McIntire

Published

June 18, 2024

The objective of this book is to facilitate lightweight project code and setting up R3T workflows1. To do this, packages and any code that are used must be easy to install and use. We accomplish this by having each chapter installing its own packages, and avoiding having users “pre-installing” packages.

Furthermore, packages, once installed for one project, will be cached locally so that the next project will be able to install quickly from the local package cache. We have also attempted to allow all sections to be run without administrator privileges.

Nonetheless, there might be situations where users of this book will need to pre-install packages in one go – e.g., they will run chapter code without internet access. The following instructions are meant to cover this use case.

2.1 Installation code

If you can run the following code, then you will be able to run code in any of the chapters in this book. This code begins by installing SpaDES.project and its dependencies, then uses setupProject to download and install a list of R packages hosted on GitHub and a single SpaDES module (Biomass-core) which has over 130 package dependencies.

Code
repos <- c("predictiveecology.r-universe.dev", getOption("repos"))
install.packages(c("Require", "SpaDES.project"), repos = repos)

library(SpaDES.project)

out <- setupProject(
  packages = "PredictiveEcology/PredictiveEcology.org@training-book/training/R/pkgList.R",
  options = list(repos = repos),
  name = "Introduction",
  modules = "PredictiveEcology/Biomass_core@main"
)

Note that setupProject will change your working directory to ./Introduction. If that is not where you want to keep working, restart R and make sure you set your working directory to where you want it to be (if restarting is not sufficient).

2.2 Code explained

If you care to know what the code is “doing”, read on.

The setupProject call above internally uses Require to download and install any missing packages. Although the packages themselves are installed in a folder inside ./Introduction/ (the project folder) (see .libPaths() after running the code), Require caches the downloaded package installation files in a user-accessible folder (so independent from any project).

This means that, should you, e.g., switch projects and attempt to reinstall the same or a subset of these packages, setupProject (via Require) would access the package cache and reinstall them in whatever new project folder library. This is much faster than downloading the packages again.

The same is true should you lose internet connection, since the downloads do not need to happen again.

2.3 See also

Chapter 3 on R package installation troubleshooting


  1. See this introduction to R3T workflows.↩︎