使用 try/catch 省略函数的 return

Omitting the return of function with try/catch

我创建了一个脚本来使用 try/catch 自动加载包,所以我想将脚本的 returns 除了 messages 压缩到 try blocks .

但是,当执行下面的代码时,return 包含包名称的列表被 return 编辑到 Console

## Install Packages
# install.packages(httr)
# install.packages(jsonlite)
# install.packages(lubridate)
# install.packages(dplyr)
# install.packages(openxlsx)
# install.packages(tibble)
# install.packages(tidyr)
# install.packages(stringr)

# Store package names into a vector
pacotes <- c('httr', 'jsonlite', 'lubridate', 'dplyr', 'openxlsx', 'tibble', 'tidyr', 'stringr')

fun.loadPacotes <- function(pacotes) {
  out <- tryCatch(
    {

      invisible(lapply(pacotes, library, character.only = TRUE))

    },
    error=function(cond) {

      message(paste("FAIL TO LOAD:", pacotes))

      message("Error Message:")

      message(cond)

    },
    warning=function(cond) {

      message(paste("The package return a warning:", pacotes))

      message("Warning Message:")

      message(cond)

    },
    finally={

      message(paste("Package Loaded:", pacotes))

    }
  )    
  return(out)
}

# Run function and load the packages
lapply(pacotes, fun.loadPacotes)

当我运行命令invisible(lapply(pacotes, library, character.only = TRUE))时,return没问题,Console没有结果。

我想运行这段代码,这样它就不会return包名列表。

你的函数 returns out。如果它返回 invisible(out),结果将是不可见的。

您在函数顶部附近调用了 invisible(),但隐身非常短暂。否则任何函数做类似

x <- someFunctionReturningInvisibleResult()
x

不会自动打印结果。所以你可以跳过靠近顶部的调用。

如果你想让隐形成为有条件的,那么你需要明确地让它成为有条件的,例如作为函数的结尾,

if (shouldBeInvisible)
  invisible(out)
else
  out

您通常不需要显式调用 return();如果需要提前返回值,您只需要使用它。但是如果你出于风格原因想使用它,上面的行可以用冗余调用来编写,比如

if (shouldBeInvisible)
  return(invisible(out))
else
  return(out)