如何在 R 中检测警告并在输出警告时在函数上运行 while 循环?

  • 本文关键字:警告 运行 函数 while 循环 输出 r rstan
  • 更新时间 :
  • 英文 :


我目前正在R运行rstan包中的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 循环来重新运行函数,直到我遇到没有警告的运行。有没有办法标记或检测上述警告消息?谢谢。

您可以使用 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 
}

最新更新