当 R 中的循环中出现警告时,是否可以报告并提取它发生在哪个迭代中?

use*_*627 7 r

我目前有一些代码正在循环回归模型,并且对于某些迭代,会出现一条警告消息。例如:

for(i in 1:100){
    set.seed(i)  
    x  = c(runif(100, min=-3, max=3), 200)
    y  = rbinom(101, size=1, prob=1/(1+e^(-x))
    m  = glm(y~x, family=binomial)
}
Run Code Online (Sandbox Code Playgroud)

将会出现警告glm(y~x, family=binomial),但仅在最后报告:

 There were 50 or more warnings (use warnings() to see the first 50)
Run Code Online (Sandbox Code Playgroud)

有没有办法查看哪个迭代导致了哪些警告,并能够最终报告导致警告的结果?

pla*_*pus 7

使用tryCatch

for(i in 1:100){ 
  set.seed(i)                        
  x  = c(runif(100, min=-3, max=3), 200) 
  y  = rbinom(101, size=1, prob=1/(1+exp(-x)))
  tryCatch({m   <-  glm(y~x, family=binomial)}, warning=function(w) print(i))
}
Run Code Online (Sandbox Code Playgroud)