1 Packages
library(renv)
2 Motivation
Assume you find a cool repo or some online-book and you want to run the R code.
You might want to check if you have all the required packages installed.
This is what this post is about. We will use the usethis
package to check if all required packages are installed.
3 Find out missing packages
Of course, in some R project you can and should check the DESCRIPTION
file for details on the needed or suggested R pacakges.
But, for projects other than R packages (and even for R packages), there’s a function that checks the dependencies:
deps <- dependencies(path = "content", quiet = FALSE, progress = TRUE)
deps$Package |> unique() |> head()
Okay, now we know which packages are needed.
You may want to save the list of your installed packages. This may prove handy after updating a new version of R such as from 4.4.0 to 4.5.
writeRDS(deps, "deps.rds")
4 Install missing packages from CRAN
Next, we can install them if they are not already installed:
install_if_missing <- function(package) {
if (!require(package, character.only = TRUE)) {
install.packages(package)
}
}
Note that this function is not perfect. It does not check the version of the package. In addition, it only installs from CRAN.
Loop through the list and install any missing packages:
invisible(lapply(deps$Package, install_if_missing))
5 Install non-CRAN packages
If you have non-CRAN packages, you can install them from GitHub or other sources:
library("remotes")
install_github("sebastiansauer/prada")