尝试编写一个安装包(如果尚未安装)的函数,然后加载它

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

我正在尝试编写一个函数来检查是否安装了某个软件包,如果没有安装则安装它,然后包含它。

我第一次尝试

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

但是使用此代码无法正确通过包名称。

经过更多搜索,我尝试了:

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

loadLibraryAndInstallPackageIfNotFound(envDocument);
loadLibraryAndInstallPackageIfNotFound(kableExtra);

我想知道我是否在其中过度使用了 character.only = TRUE...

但我现在得到:

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

是否有使该功能起作用的解决方案?

如果我们将参数作为字符串传递,就可以了

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

loadLibraryAndInstallPackageIfNotFound("envDocument");

否则,将未加引号的 'name' 转换为带有 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);