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

时间:2018-05-27 22:53:09

标签: r rstan

我目前正在stan_glm的{​​{1}}包中运行stan_glmerrstan等功能。我调用每个函数1000次,结果发现大约75%的运行会导致警告,例如:

R

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

1 个答案:

答案 0 :(得分:3)

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