Check for installed packages before running install.packages() [duplicate]
Solution 1:
try: require("xtable")
or "xtable" %in% rownames(installed.packages())
Solution 2:
If you want to do it as simply as possible:
packages <- c("ggplot2", "dplyr", "Hmisc", "lme4", "arm", "lattice", "lavaan")
install.packages(setdiff(packages, rownames(installed.packages())))
Replace the packages listed on the first line by those needed to run your code, and voilà!
Note: Edited to remove conditional wrapper thanks to Artem's comment below.
Solution 3:
This is a function I often used to check for a package, install it otherwise and load again:
pkgTest <- function(x)
{
if (!require(x,character.only = TRUE))
{
install.packages(x,dep=TRUE)
if(!require(x,character.only = TRUE)) stop("Package not found")
}
}
Works like pkgTest("xtable")
. It only works if the mirror is set though, but you could enter that in the require
calls.
Solution 4:
I suggest a more lightweight solution using system.file
.
is_inst <- function(pkg) {
nzchar(system.file(package = pkg))
}
is_inst2 <- function(pkg) {
pkg %in% rownames(installed.packages())
}
library(microbenchmark)
microbenchmark(is_inst("aaa"), is_inst2("aaa"))
## Unit: microseconds
## expr min lq mean median uq max neval
## is_inst("aaa") 22.284 24.6335 42.84806 34.6815 47.566 252.568 100
## is_inst2("aaa") 1099.334 1220.5510 1778.57019 1401.5095 1829.973 17653.148 100
microbenchmark(is_inst("ggplot2"), is_inst2("ggplot2"))
## Unit: microseconds
## expr min lq mean median uq max neval
## is_inst("ggplot2") 336.845 386.660 459.243 431.710 483.474 867.637 100
## is_inst2("ggplot2") 1144.613 1276.847 1507.355 1410.054 1656.557 2747.508 100