我正在使用来自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()仍然会打印错误。发布于 2018-07-03 05:41:59
这是因为fitdist (或者实际上是fitdist调用的mledist )已经在执行一些错误捕获操作。原始错误在optim中并已被捕获,然后mledist将错误消息打印到控制台。因此,您所看到的并不是真正的错误,甚至不是警告,而是带有捕获错误信息内容的打印语句。
执行此操作的mledist部分是:
if (inherits(opttryerror, "try-error")) {
warnings("The function optim encountered an error and stopped.")
if (getOption("show.error.messages"))
print(attr(opttryerror, "condition"))
return(list(estimate = rep(NA, length(vstart)), convergence = 100,
loglik = NA, hessian = NA, optim.function = opt.fun,
fix.arg = fix.arg, optim.method = meth, fix.arg.fun = fix.arg.fun,
counts = c(NA, NA)))
}这并不是很好的实践,正是因为它导致了您现在的问题;它阻止了其他人系统地处理错误。
从该代码中可以看到,可以通过将show.error.messages选项设置为FALSE来关闭此选项:
options(show.error.messages = FALSE)但是您需要小心,因为在R会话的其余部分,您不会看到任何错误消息。你肯定不想在别人的会议上这么做。
另一种选择是使用sink("extra-error-messages.txt")将所有打印发送到控制台某个位置(甚至可能发送到您的error_log.txt,但我不确定这是否会导致写入多个内容时出现问题)。
https://stackoverflow.com/questions/51132359
复制相似问题