Trying to write a function that installed a package if not already installed, then load it

Viewed 47

I am trying to write a function that can check if a package is installed, will install it if it is not, and then include it.

I first tried

loadLibraryAndInstallPackageIfNotFound <- function(name) {
  if(!require(name))
    install.packages(name);
  library(name);
}

But the package name is not going through correctly using this code.

After some more search I tried:

loadLibraryAndInstallPackageIfNotFound <- function(name) {
  if(!require(name,character.only = TRUE))
    install.packages(name,character.only = TRUE);
  library(name,character.only = TRUE);
}

loadLibraryAndInstallPackageIfNotFound(envDocument);
loadLibraryAndInstallPackageIfNotFound(kableExtra);

I'm wondering if I'm over-using character.only = TRUE in there...

But I'm now getting:

Error in paste0("package:", package) : object 'envDocument' not found

Is there a solution to make this function work?

1 Answers

If we pass the argument as a string, it would work

loadLibraryAndInstallPackageIfNotFound <- function(name) {
  if(!require(name,character.only = TRUE))
    install.packages(name,character.only = TRUE);
  library(name,character.only = TRUE);
}

loadLibraryAndInstallPackageIfNotFound("envDocument");

Otherwise, convert the unquoted 'name' to a string with deparse/substitute

loadLibraryAndInstallPackageIfNotFound <- function(name) {
  name <- deparse(substitute(name))
  if(!require(name,character.only = TRUE))
    install.packages(name,character.only = TRUE);
  library(name,character.only = TRUE);
}

loadLibraryAndInstallPackageIfNotFound(envDocument);
Related