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

How to detect warnings in R and have a while loop run on a function as along as warnings are outputted?

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

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

但是,在使用 repeat 和 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 
}