I am fitting a logistic growth model for each subject.
When I run my loop to fit the model for every patient. There is an error as some patients the model does not converge as they do not have a logistic growth. I want my loop to continue if there is an error in fitting the model and just have NA's in the dataset where I am capturing the coefficients
growth_rate_l <- function(patient, data) {
data0 <- data %>% dplyr::filter(pat== patient)
fit0 <- nls(MRDRSLT ~ SSlogis(TIME, phi1, phi2, phi3), data = data0)
t_doubling <- (summary(fit0)$coefficients)
aic <-AIC(fit0, k=3)
outdata <- c(t_doubling,aic)
outdata
}
for (i in unique(doub1log$pat)) {
doub1log$phi1[doub1log$pat== i] <- growth_rate_l(i, doub1log)[1]
doub1log$phi2[doub1log$pat== i] <- growth_rate_l(i, doub1log)[2]
doub1log$phi3[doub1log$pat == i] <- growth_rate_l(i, doub1log)[3]
doub1log$AIC[doub1log$pat== i] <- growth_rate_l(i, doub1log)[13]
}
For some subjects the model will not fit and I get an error from nls
Error in nls(y ~ 1/(1 + exp((xmid - x)/scal)), data = xy, start = list(xmid = aux[[1L]], : step factor 0.000488281 reduced below 'minFactor' of 0.000976562
Once it errors the loop stops, but I want it to carry until the end and have NA's for subjects whose models cannot be fitted.
I tried "try" and "tryCatch" but it is not intuitive any ideas on how to deal with this issue?
I tried tryCatch(, error = function(e) { skip_to_next <<- TRUE}) if(skip_to_next) { next } ``` i tired this in the loop above
I put this in the loop above but it is not working. I am unsure whether I need to capture the error in the loop or in the function.
I used to be a stata user and it had a command called capture which allowed a loop to run regardless of error.