9

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!

Mayou
  • 8,498
  • 16
  • 59
  • 98

1 Answers1

12

I have this convenience function that I use instead of library which installs the package if it is missing, then requires 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)
Alex Vorobiev
  • 4,349
  • 21
  • 29
  • 1
    It seems to me that the behaviour of `require()` depends on the R editor. While `require()` works as described above in RKward, it did not using RStudio. Instead, RStudio gives a warning message. Therefore `require(XXX) || install.packages("XXX")` is safer because it always works, regardless of the editor you are using. – MERose Oct 17 '14 at 19:17