Install package (library) if not installed
I have this convenience function that I use instead of library
which installs the package if it is missing, then require
s it:
usePackage <- function(p) {
if (!is.element(p, installed.packages()[,1]))
install.packages(p, dep = TRUE)
require(p, character.only = TRUE)
}
In case if you need to select CRAN mirror globally, here is one way to do it:
r <- getOption("repos")
r["CRAN"] <- "http://cran.us.r-project.org"
options(repos = r)
rm(r)
Comments
-
Mayou almost 2 years
I am using a couple of packages in R, but I am running the script in a machine that may or may not have some/all of the packages installed already.
The packages are
zoo
,quantmod
,data.table
,..., and a bunch more.This is what I have tried: Is there any way of checking if each of these packages is installed, if not install it? I don't want R to waste time reinstalling any package that is already there.
This is what I have tried:
pckg = c("zoo", "tseries", "quantmod", "MASS", "graphics", "plyr", "data.table", "gridExtra") is.installed <- function(mypkg){ is.element(mypkg, installed.packages()[,1]) } for(i in 1:length(pckg)) { if (!is.installed(pckg[i])){ install.packages(pckg[i]) } }
Is there a better way of doing that?
Also, I need to automatically set a mirror for the install.I have no idea how to do so.
Thanks!
-
MERose over 9 yearsIt seems to me that the behaviour of
require()
depends on the R editor. Whilerequire()
works as described above in RKward, it did not using RStudio. Instead, RStudio gives a warning message. Thereforerequire(XXX) || install.packages("XXX")
is safer because it always works, regardless of the editor you are using.