Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

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?

like image 522
user321627 Avatar asked Jan 30 '23 22:01

user321627


2 Answers

Use 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))
}
like image 195
platypus Avatar answered Feb 03 '23 04:02

platypus


See tryCatch, argument finally.

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)))
 m  <- tryCatch(glm(y~x, family = binomial), finally = print(i))
}

Also, I've changed the equal sign to the assignment arrow <-.

like image 24
Rui Barradas Avatar answered Feb 03 '23 03:02

Rui Barradas