Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if R package is installed then load library

Tags:

r

Our R scripts are used on multiple users on multiple computers and hence there are deviations in which packages are installed on each computer. To ensure that each script works for all users I would like to define a function pkgLoad which will first test if the package is installed locally before loading the library with suppressed startup messages. Using Check for installed packages before running install.packages() as a guide, I tried

 pkgLoad <- function(x)
  {
    if (!require(x,character.only = TRUE))
    {
      install.packages(x,dep=TRUE, repos='http://star-www.st-andrews.ac.uk/cran/')
      if(!require(x,character.only = TRUE)) stop("Package not found")
    }
    #now load library and suppress warnings
    suppressPackageStartupMessages(library(x))
    library(x)
  }

When I try to load ggplot2 using pkgLoad("ggplot2") I get the following error message in my terminal

Error in paste("package", package, sep = ":") : object 'ggplot2' not found > pkgLoad("ggplot2") Loading required package: ggplot2 Error in library(x) : there is no package called ‘x’ > pkgLoad("ggplot2") Error in library(x) : there is no package called ‘x’

Any why x changes from ggplot2 to plain old x?

like image 996
moadeep Avatar asked Mar 01 '13 10:03

moadeep


1 Answers

I wrote this function the other day that I thought would be useful...

install_load <- function (package1, ...)  {   

   # convert arguments to vector
   packages <- c(package1, ...)

   # start loop to determine if each package is installed
   for(package in packages){

       # if package is installed locally, load
       if(package %in% rownames(installed.packages()))
          do.call('library', list(package))

       # if package is not installed locally, download, then load
       else {
          install.packages(package)
          do.call("library", list(package))
       }
   } 
}
like image 172
maloneypatr Avatar answered Oct 16 '22 20:10

maloneypatr