The renv
package does all sorts of fancy things: installing from several different locations, setting up a project-specific library so that you can control the versions for a project, etc. If you need that stuff, I think you're out of luck. As far as I can see it has no way to pass in a list of dependencies, it needs to scan your source to find them. I suppose you could include a function like
loadPackages <- function() {
requireNamespace("foo")
requireNamespace("bar")
...
}
to make it easier for renv
to find your required packages, but if it's failing in some other way (e.g. you have incomplete files that don't parse properly), this won't help.
If you don't need all that fancy stuff, you could use the function below:
needsPackages <- function(pkgs, install = TRUE, update = FALSE,
load = FALSE, attach = FALSE) {
missing <- c()
for (p in pkgs) {
if (!nchar(system.file(package = p)))
missing <- c(missing, p)
}
if (length(missing)) {
missing <- unique(missing)
if (any(install)) {
toinstall <- intersect(missing, pkgs[install])
install.packages(toinstall)
for (p in missing)
if (!nchar(system.file(package = p)))
stop("Did not install: ", p)
} else
stop("Missing packages: ", paste(missing, collapse = ", "))
}
if (any(update))
update.packages(oldPkgs = pkgs[update], ask = FALSE, checkBuilt = TRUE)
for (p in pkgs[load])
loadNamespace(p)
for (p in pkgs[attach])
library(p, character.only = TRUE)
}
which is what I've used in one project. You call it as
needsPackages(c("foo", "bar"))
and it installs the missing ones. It can also update, load, or attach them. It's just using the standard function install.packages
to install from CRAN,
no fancy selection of install locations, or maintenance of particular package versions. If you do use something simple like this, you should run sessionInfo()
afterwards to record package version numbers, in case you need to return to the same state later. (Though returning to that state will probably be painful!)