【问题标题】:How to detect warnings in R and have a while loop run on a function as along as warnings are outputted?如何检测 R 中的警告并在函数上运行 while 循环以及输出警告?
【发布时间】:2018-05-27 22:53:09
【问题描述】:

我目前正在运行Rrstan 包中的stan_glmstan_glmer 等函数。我将每个函数调用了 1000 次,结果发现其中大约 75% 的运行会导致以下警告:

Warning messages:
1: There were 184 divergent transitions after warmup. Increasing adapt_delta above 0.95 may help. See
http://mc-stan.org/misc/warnings.html#divergent-transitions-after-warmup 
2: There were 1 chains where the estimated Bayesian Fraction of Missing Information was low. See
http://mc-stan.org/misc/warnings.html#bfmi-low 
3: Examine the pairs() plot to diagnose sampling problems
4: Markov chains did not converge! Do not analyze results! 

我想创建一个 while 循环来重新运行该函数,直到遇到没有警告的运行。有没有办法标记或检测上述警告消息?谢谢。

【问题讨论】:

    标签: r rstan


    【解决方案1】:

    您可以使用 tryCatch() 函数来捕捉错误和警告,并根据结果调整您的工作流程,即:

    x = -3.5
    
    repeat{
    
      x <- x + 0.6
      print( paste("Current value of x is", x) )
    
      result <- tryCatch( log( x ), 
                          error = function(e) e, 
                          warning = function(w) w ) 
    
      if (inherits(result,"warning")) next  # For warnings - continue the next iteration
      if (inherits(result,"error")) stop( result )  # For errors - stop
    
    
      print( paste0(" log(",x,")=", result))
      break 
    }
    
    # [1] "Current value of x is -2.9"
    # [1] "Current value of x is -2.3"
    # [1] "Current value of x is -1.7"
    # [1] "Current value of x is -1.1"
    # [1] "Current value of x is -0.5"
    # [1] "Current value of x is 0.1"
    # [1] " log(0.1)=-2.30258509299404"
    

    但是,对于重复和 while 循环要非常小心,因为您最终可能会创建一个无限循环。检查循环执行了多少次迭代并在迭代次数过多时中止它可能是个好主意:

    x = -3.5
    iter <- 0
    
    while (iter < 100) {
    
      x <- x + 0.6
      iter <- iter + 1
    
      print( paste("Current value of x is", x) )
    
      result <- tryCatch( log( x ), 
                          error = function(e) e, 
                          warning = function(w) w ) 
    
      if (inherits(result,"warning")) next  # For warnings - continue the next iteration
      if (inherits(result,"error")) stop( result )  # For errors - stop
    
    
      print( paste0(" log(",x,")=", result))
      break 
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-07
      • 2018-06-05
      • 2017-09-26
      • 2018-09-26
      • 2016-06-21
      • 2017-10-13
      • 2012-01-03
      • 2018-03-25
      相关资源
      最近更新 更多