Yossi Levy
Yossi Levy

Reputation: 79

How to prevent simulation stopping when lmer model does not converge

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.

Upvotes: 1

Views: 425

Answers (1)

jay.sf
jay.sf

Reputation: 72683

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.

Upvotes: 1

Related Questions