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

Suppress error message when using fitdist() from the fitdistrplus package

我正在使用 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() 打印此错误消息。

我已经尝试过以下替代方案:

  1. try()silent = TRUE。错误消息仍然被打印出来。
  2. conditionMessage() 给出相同的结果。
  3. withCallingHandlers() 已在一些帖子和话题中提出,但我不确定如何正确实施它。
  4. 在函数中使用 invisible() 仍然打印错误。

这是因为 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 但我不确定这是否会导致多个内容写入的问题它)。