Install package (library) if not installed

17,426

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)
Share:
17,426
Mayou
Author by

Mayou

Quant at an investment management firm.

Updated on July 24, 2022

Comments

  • Mayou
    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
    MERose over 9 years
    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.