从fitdistrplus包中使用fitdist()时抑制错误消息

时间:2018-07-02 08:55:12

标签: r error-handling try-catch error-suppression fitdistrplus

我正在使用fitdistrplus包中的某些功能作为我正在创建的包的一部分。

我正在尝试防止在运行功能时在控制台中显示任何错误消息,而是希望将错误消息记录在我正在创建的错误日志中。

在大多数情况下,使用tryCatch()可以实现这一目标。

但是专门针对fitdist()函数,即使消息已被写入错误日志(这意味着tryCatch()表达式正在起作用),我也无法抑制在控制台中打印该错误消息。 / p>

我已在下面的代码中复制了我的问题。

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()打印。

我已经尝试了以下替代方法:

  1. try()silent = TRUE。错误消息仍会打印。
  2. conditionMessage()给出相同的结果。
  3. 在某些帖子和主题中建议使用
  4. withCallingHandlers(),但我不确定如何正确实施。
  5. invisible()与函数一起使用仍会打印错误。

1 个答案:

答案 0 :(得分:2)

这是因为fitdist(实际上是mledist所调用的fitdist)已经在进行错误捕获了。原始错误位于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,但是我不确定这是否会导致写入多个内容的问题)