代码之家  ›  专栏  ›  技术社区  ›  Rage

从fidtreplus包中使用fidtist()时禁止显示错误消息

  •  2
  • Rage  · 技术社区  · 8 年前

    我正在使用 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() 函数仍然打印错误。
    1 回复  |  直到 8 年前
        1
  •  2
  •   Peter Ellis    8 年前

    这是因为 fitdist (或者实际上, mledist 它是由 菲迪斯特 )已经在进行错误捕获。原始错误在 optim 被抓住了,然后 姆雷迪斯特 印刷品 向控制台发送错误消息。所以你看到的不是一个错误,甚至是一个警告,而是一个包含捕获到的错误消息内容的打印语句。

    一点点的 姆雷迪斯特 这样做是:

        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 选择错误:

    options(show.error.messages = FALSE)
    

    但您需要小心,因为在R会话的其余部分不会看到任何错误消息。你肯定不想参加别人的会议。

    另一种选择是使用 sink("extra-error-messages.txt") 把所有的打印发送到控制台的某个地方(甚至可能发送到 error_log.txt 但我不确定这是否会导致写多个东西的问题。

    推荐文章