0

I'm fitting two mixed-effects regression models to data samples in a for-loop and writing model summaries to file. I diverted the console stream to a text file so I can keep track any warnings or errors. I'm handling the errors with tryCatch()so that my loop does not stop after an error.

As far as I can tell, there are two issues with my code. First, when I query the returned exception in tryCatch(), e.g. poss.err.mod1 I get the following error:

<simpleError in tryCatchList(expr, classes, parentenv, handlers): argument "expr" is missing, with no default>

Still, the warnings are correctly written to file, which is puzzling. Second, when no error is detected, the code seems to be ignored (i.e. no model summaries are written to file). So the loop is running vacuously, skipping errors but apparently handling them and doing nothing else. What am I doing wrong?

N.B. My code is modeled on this SO post.

# divert console stream to file
options(warn=1)
wngs=file("warnings_log.txt",open="w+",blocking=TRUE)
sink(wngs,type="message")

for(iter in 1:1000){

  data = read.csv(paste("sample", iter,".csv", sep=""), header=TRUE)

  #error handling case #1 
  poss.err.mod1 = tryCatch(

    lmer(y ~ x1 + (1|ranef), data = data, REML = FALSE), #try part
    error=function(e) e #catch part
  )

  #error handling case #2
  poss.err.mod2 = tryCatch(

    lmer(y ~ x1 + x2 + (1|ranef), data = data, REML = FALSE), #try part
    error=function(e) e #catch part
  )

  #real work #1
  if(!inherits(poss.err.mod1, "error")){

    mod1 = lmer(y ~ x1 + (1|ranef1), data = data, REML = FALSE)
    write.csv(summmary$mod2, paste("mod2.sum_", iter, ".csv", sep="")

  }else{

    write(unlist(mod1@optinfo$conv$lme4$messages), paste("mod1.errors_", iter, ".txt", sep=""))
  }

  #real work #2
  if(!inherits(poss.err.mod2, "error")){

    mod2 = lmer(y ~ x1 + x2 + (1|ranef1), data = data, REML = FALSE)
    write.csv(summmary$mod2, paste("mod2.sum_", iter, ".csv",)

  }else{

    write(unlist(mod2@optinfo$conv$lme4$messages), paste("mod1.errors_", iter, ".txt", sep=""))
  }

  cat("Iteration", iter, "completed!\n")
}

#close log file & restore warnings stream to console
closeAllConnections()
Des Grieux
  • 520
  • 1
  • 5
  • 31
  • 1
    if there is no error, mod1/mod2 are never created so there is nothing to write. and you don't need the conditional since you are using tryCatch, just try something like `tryCatch({lmer; write}, error = function(e) {lmer; write})` which will greatly simplify your code – rawr Mar 23 '18 at 22:08
  • That makes sense, but does it resolve the issue of the missing "expr" argument? in poss.err.modX? Why is the error not returned? – Des Grieux Mar 23 '18 at 22:28
  • 1
    some kind of syntax error, eg, `tryCatch()` reproduces the error, without a reproducible example, there's not much more to do – rawr Mar 23 '18 at 22:35
  • 2
    you also have `summmary$mod2` under the mod1 conditional – rawr Mar 23 '18 at 22:44

0 Answers0