How can I tell if a certain package was already installed?

r, rstudio

Solution

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.

Problem

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?

Original source