r - Use tryCatch() but don't overwrite object when error/warning encountered -
i want iteratively fit lmer() model within for loop , store results. when encounter error, don't want mermod object (the output lmer() model) overwrite mermod object previous iteration. example:
# install.packages(c("lme4", "dplyr", "ggplot2"), dependencies = true) library("lme4") library("dplyr") library("ggplot2") predlist <- list() j <- 1 for(i in 2:9){ tr <- sleepstudy %>% filter(days < i) pr <- sleepstudy %>% filter(days == i) fm <- trycatch({lmer(reaction ~ days + (1|subject), data=sleepstudy)}, warning = function(w) {#code move along `predict` without overwriting `fm`}, error = function(e) {#code move along `predict` without overwriting `fm`}) #predict reaction pr$prre <- predict(fm, pr) predlist[[j]] <- pr j = j + 1 } pred <- bind_rows(predlist) %>% arrange(subject, days) ggplot(data=pred, aes(reaction, prre)) + geom_point() this code runs no problem. however, let's when i=4, error lmer(). when happens, don't want replace fm error message. instead, want leave fm (the model output when i=3) , move along predict statement comes after lmer(). how can that?
a special case might when first iteration fails. let's not worry that. assume first iteration of loop fits lmer() model.
one solution might doing like:
# install.packages(c("lme4", "dplyr", "ggplot2"), dependencies = true) library("lme4") library("dplyr") library("ggplot2") predlist <- list() j <- 1 for(i in 2:9){ tr <- sleepstudy %>% filter(days < i) pr <- sleepstudy %>% filter(days == i) fm <- trycatch({lmer(reaction ~ days + (1|subject), data=sleepstudy)}, warning = function(w) {message(w)}, error = function(e) {message(e)}) #if model did not fail, predict usual , store fm in fm0. if model did fail, use fm0 previous iteration prediction if(is.null(fm)){ pr$prre <- predict(fm0, pr) } else {fm0 <- fm pr$prre <- predict(fm, pr) } predlist[[j]] <- pr j = j + 1 } but that's little verbose. there simple can put within trycatch() function not overwrite fm , move along next statement when model fails?
i can think of solution, first if want not overwrite fm , go next statement:
initialize fm initial model fm0:
fm <- fm0 then run loop:
for ( in 2:9 ){ fm <- trycatch({lmer(reaction ~ days + (1|subject), data=sleepstudy)}, error = function(e){return(fm)}) #return previous value of fm if error # else } however don't understand why have 2 indices i , j. notice j starts value of 1, , i starts value of 2. in each iteration both values increment 1 because of last line j = j + 1 in next iteration j 2, , iis 3 , on. code same if do
for (j in 1:8){ <- j+1 #your code here } and looks better imho.
Comments
Post a Comment