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!
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With