首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何检测R中的警告,并在输出警告的同时在函数上运行while循环?

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

Stack Overflow用户
提问于 2018-05-28 06:53:09
回答 1查看 731关注 0票数 0

我目前正在从Rrstan包中运行stan_glmstan_glmer等函数。我对每个函数调用了1000次,结果发现大约75%的运行都会产生如下警告:

代码语言:javascript
复制
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循环来重新运行这个函数,直到我遇到一个没有警告的运行。有没有办法标记或检测上面这样的警告消息?谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-05-28 10:22:00

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

代码语言:javascript
复制
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循环,因为您可能最终会创建无限循环。检查循环执行了多少次迭代并在迭代次数过多的情况下中止它可能是一个好主意:

代码语言:javascript
复制
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 
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50557228

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档