【问题标题】:Omitting the return of function with try/catch用 try/catch 省略函数的返回
【发布时间】:2019-08-02 18:13:06
【问题描述】:

我创建了一个脚本来使用try/catch 自动加载包,所以我想将除messages 之外的脚本返回到try blocks

但是,当执行下面的代码时,带有包名称的列表的返回将在 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))时,返回正常,Console没有结果。

我想运行此代码,以便它不返回包名称列表。

【问题讨论】:

  • (1) 我想知道您是否需要withCallingHandlers(可能使用invokeRestart("muffleWarning"))而不是tryCatch,因为一旦引入一个警告,后者将终止您的expr 的执行.您是否打算在收到警告后继续操作? (2) 来自fun.loadPacotes 的返回值将是invisible,但不是来自lapply(它忽略了一些不可见的东西并愉快地返回其值可见)。如果您手动执行fun.loadPacotes(pacotes[1]),它将如您预期的那样不可见。 (同样,lapply(1:2, invisible) 将永远不可见。)

标签: r machine-learning rstudio data-science


【解决方案1】:

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

您在函数顶部附近调用了invisible(),但不可见性非常短暂。否则任何类似

的函数
x <- someFunctionReturningInvisibleResult()
x

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

如果您希望不可见是有条件的,那么您需要明确地使其有条件,例如作为函数的结束,

if (shouldBeInvisible)
  invisible(out)
else
  out

您通常不需要显式调用return();如果需要提前返回值,您只需要使用它。但是如果你出于文体原因想使用它,上面的行可以用像

这样的冗余调用来编写
if (shouldBeInvisible)
  return(invisible(out))
else
  return(out)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-13
    • 2016-01-15
    • 2014-04-27
    • 1970-01-01
    • 1970-01-01
    • 2012-05-18
    • 2018-11-05
    相关资源
    最近更新 更多