Tuesday, 28 June 2016

R Install Required Packages

When using R, if there is a script with multiple packages that might not be installed, it can take some time to go through the list and check they are all installed.

Instead of using the "require(packagename)" command, I used the following script to load packages

pkgTest <- function(x)
{
  if (!require(x,character.only = TRUE))
  {
    install.packages(x,dep=TRUE)
    if(!require(x,character.only = TRUE)) stop("Package not found")
  }
}

This script tries to load the package using the "require" command, and if this is not successful then will try to install it. It then tries the "require" command once more, and if not successful will stop the code execution.

No comments:

Post a Comment