【发布时间】:2018-12-10 10:57:19
【问题描述】:
我正在使用fitdistrplus 包中的某些函数作为我正在创建的包的一部分。
我试图阻止在运行函数时在控制台中显示任何错误消息,而是希望将错误消息记录在我正在创建的错误日志中。
在大多数情况下,使用tryCatch() 让我能够实现这一点。
但特别是对于 fitdist() 函数,即使正在将消息写入错误日志(意味着 tryCatch() 表达式正在运行),我也无法禁止在控制台中打印错误消息。
我在下面的代码中复制了我的问题。
library(fitdistrplus)
file.create("error_log.txt")
func_desc<-function(x){
tryCatch({
descdist(data = x)
},error = function(e){
write(x = paste(Sys.time(),"Error in func_desc :",e$message,sep = " "),file = "error_log.txt",append = T,sep = "\n")
})
}
func_fit<-function(x,dist){
tryCatch({
fitdist(data = x,distr = dist)
},error = function(e){
write(x = paste(Sys.time(),"Error in func_fit :",e$message,sep = " "),file = "error_log.txt",append = T,sep = "\n")
})
}
# Creating a vector of repeated values which will result in an error
test<-rep(x = 1,times = 10)
func_desc(x = test)
# Results in an error and the message is written to the error log and not printed in the console
func_fit(x = test,dist = "beta")
# Results in an error and the message is both written to the error log and printed in the console
我想禁止func_fit() 打印此错误消息。
我已经尝试过以下替代方案:
-
try()和silent = TRUE。仍然会打印错误消息。 -
conditionMessage()给出相同的结果。 -
withCallingHandlers()已在一些帖子和线程中提出,但我不确定如何正确实施。 - 将
invisible()与函数一起使用仍会打印错误。
【问题讨论】:
-
嘿,我认为问题是,您的错误消息来自 C 代码。 optim 调用源
.External2(C_optim, par, fn1, gr1, method, con, lower, upper)中的 C_optim 文件调用 C_optim 函数。由于我不确定错误是否有这个起源,所以我没有写这个作为答案。这可以解释为什么你不能静音。 (见here)所以要么这对你有用,要么另一种方法是(不推荐)重写源代码。 -
感谢您的回复。我尝试使用该线程中建议的解决方案,但 CRAN 上不再提供
multicore包。multicore页面说parallel可以用作替代方案。我已经浏览了它的文档,但我不知道如何在我的情况下使用它。
标签: r error-handling try-catch error-suppression fitdistrplus