Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Install package (library) if not installed [duplicate]

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!

like image 645
Mayou Avatar asked Oct 25 '13 17:10

Mayou


1 Answers

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)
like image 149
Alex Vorobiev Avatar answered Oct 04 '22 19:10

Alex Vorobiev