1

I run a simulation in which I have a loop similar to this

simulate_study <- function(params){
  pats <- simulate_pats(params) # a function that simulate the pats data frame
  model <- lmer(SFD ~ group*month + (1 + month|id), data=pats, REML=TRUE)
  reject <- as.numeric(confint(model, method="Wald")[8, 1] > 0)
  return(reject)
}
res <- sapply(1:1000, FUN=simulate_study, params=some_values)

Sometimes the model does not converge, and I get the following error message:

Error in eigen(Sigma, symmetric = TRUE) : 
  infinite or missing values in 'x'
In addition: Warning message:
In Ops.factor(sd, 2) :
 Error in eigen(Sigma, symmetric = TRUE) : 
  infinite or missing values in 'x' 

I don't care about the error. I want the loop to keep running, but the error stops the whole loop. I tried to insert the something like this into the function

if(is.null(summary(model)$optinfo$message) == FALSE) {return(NA)}

But its too late.

I will appreciate any help.

jay.sf
  • 60,139
  • 8
  • 53
  • 110
Yossi Levy
  • 79
  • 1
  • 5
  • 1
    See `try` function. Also, the errors are about infinite or missing values, not about convergence. – user2974951 Jan 04 '22 at 09:43
  • It would be helpful to have a reproducible example (using `set.seed()` and filling in something real where you have `some_values`) in case this an edge case that could be handled better within `lmer`. – Ben Bolker Jan 04 '22 at 22:24

1 Answers1

1

Try tryCatch, as error= argument use a vector of NAs with length corresponding to the expected output. Example:

library(lme4)
simulate_study <- function(params) { 
  # pats <- simulate_pats(params) # a function that simulate the pats data frame
  reject <- tryCatch({
    # stop()  ## uncomment line to produce error and see the effect
    model <- lmer(Reaction ~ Days + (Days | Subject), sleepstudy, REML=TRUE)
    as.numeric(confint(model, method="Wald")[5:6, ] > 0)
  }, error=function(e) rep(NA, 4L))
  return(reject)
}

replicate(10L, simulate_study(params=0))  ## more suitable than `sapply` here

You could also try to use REML=FALSE, lmerControl(optCtrl=list(maxit=100L)) and look if it converges better.

jay.sf
  • 60,139
  • 8
  • 53
  • 110