When I install the yaml package, an annoying error message pops up in RStudio if it had been previously installed. How can I tell if the package was already installed so I can decide in my code whether to install the package or not?
The message is in a pop up window and it is:
One or more of the packages that will be updated by this installation
are currently loaded. Restarting R prior to updating these packages is
strongly recommended. RStudio can restart R and then automatically
continue the installation after restarting (all work and data will be
preserved during the restart). Do you want to restart R prior to
installing?
This will load yaml
, installing it first if its not already installed:
if (!require(yaml)) {
install.packages("yaml")
library(yaml)
}
or if you want to parameterize it:
pkg <- "yaml"
if (!require(pkg, character.only = TRUE)) {
install.packages(pkg)
if (!require(pkg, character.only = TRUE)) stop("load failure: ", pkg)
}
UPDATE. Parametrization.
you can use installed.packages()
to find installed packages
Alternatively, you can use the require
function. It will try to load the package and silently return a logical stating whether or not the package is available. There is also a warning if the package cannot be loaded.
test1 <- require("stats")
test1
test2 <- require("blah")
test2
I am using the following construction in my code. The essential part is about calling library
within tryCatch
and installing it if it fails:
lib.auto <- function(lib, version=NULL, install.fun=install.packages, ...) {
tryCatch(
library(lib, character.only=T),
error=function(e) {
install.fun(lib, ...)
library(lib, character.only=T)
}
)
if (!is.null(version)) {
if (packageVersion(lib) < version) {
require(devtools)
detach(paste0('package:', lib), unload=T, character.only=T)
install.fun(lib, ...)
library(lib, character.only=T)
if (packageVersion(lib) < version) {
stop(sprintf('Package %s not available in version %s. Installed version: %s', lib, version,
packageVersion(lib)))
}
}
}
}
lib.auto('BiocInstaller',
install.fun=function(lib) {
source("http://bioconductor.org/biocLite.R")
biocLite(lib)
})
options(repos=biocinstallRepos())
lib.auto.bioc <- lib.auto
lib.auto.github <- function(lib, version=NULL, user, subdir=NULL, repo=lib)
lib.auto(lib, version=version,
install.fun=function(l, u, s, r) {
require(devtools)
install_github(r, u, subdir=s)
},
user, subdir, repo
)
The lib.auto
function installs from CRAN and Bioconductor, if required. The lib.auto.github
installs from GitHub.
I am thinking about pushing this code into a package.