I am running GLMM on permuted data and for some of them I have an error message of convergence. As this is my null model, I just have to resample this specific permuted data. I thus tried to handle the tryCatch function of R but I have some failure. I have Perm which is my permuted data set of data frame and pglmm which is the glmm model for the permuted data. So I have the following structure:
pglmm<-NULL
for (i in seq_along(Perm)){
pglmm[[i]]<-summary(lme("My GLMM model"))
}
To handle the error I tried this structure
pglmm<-NULL
for (i in seq_along(Perm)){
pglmm[[i]]<- tryCatch(summary(lme()),
error=function(err){
pglmm[[i]]<- summary(lme("My GLMM model on resample data"))
return(pglmm[[i]])
}
}
For now it’s working but even by resampling once the data in which I have the error I may have a convergence problem so I need to add a while loop in order to resample until this convergence error doesn’t appear anymore. However I do not really know where to add this while loop (inside error=function(err) or should it be when starting the for loop?).
Thank you in advance for your help.
pre-allocate and fill, increment the iterator on success rather than iterating a sequence
pglmm <- vector("list", length(Perm))
i <- 1
while (i <= length(Perm)) {
pglmm[[i]] = tryCatch(summary(lme(...)), error=identity)
if (!is(pglmm[[i]], "error"))
i <- i + 1
}
or avoid the need to manage memory with
pglmm <- replicate(length(Perm), {
repeat {
result <- tryCatch(summary(lme(...)), error=identity)
if (!is(result, "error"))
break
}
result
})
Maybe something along the following lines
pglmm <- vector("list", length(Perm))
for (i in seq_along(pglmm)){
while(is.null(pglmm[[i]])) {
tryCatch(
pglmm[[i]] <- summary(lme(...)),
error = function(e) {print(e); print("retrying...")}
)
}
}
pglmm
is initialised to a list of same length as Perm
, filled with NULL
values. Going through each element of the list, you can repeat your data re-sampling and model fitting (this is the pglmm[[i]]<- ...
line) until there is no convergence error. Once a successful model run has been achieved, it is assigned to the ith entry of pglmm
and the loop then proceeds to the next index, and so on.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With