Check for installed packages before running install.packages()
try: require("xtable")
or "xtable" %in% rownames(installed.packages())
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.
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.