【发布时间】: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