When warnings occur in a loop in R, is it possible to report and extract which iteration it occurs in?

Viewed 1914

I currently have some code where I am looping over a regression model and for some iterations, there appears a warning message. For example:

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)
}

There will be warnings coming out of glm(y~x, family=binomial) but it is only reported at the end with:

 There were 50 or more warnings (use warnings() to see the first 50)

Is there a way to see which iteration caused which warnings and be able to report results in the end for those that caused warnings?

3 Answers
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({glm(y~x, family=binomial)}, warning=function(w) print(i))
}
Related