0

I want to be able to count my error/non-convergence from my lm model, which the try function skips, using a tryCatch, I will give an example of my code below so someone can help.

i =- 0
count = 0
count1 = 0
fit = rep(NA, 1000)

while(i < 1000) try({ 
    count1 = count1 + 1
    dat = sample(data,replace = T)
    fit[i] = lm(y~x1 + x2, data = dat)
    count <- count + 1
}, silent = T)

I have this code above that runs smoothly but sometimes because I resample the data, model does not converge and hence the use of try function, and I need to count the number of times that the model doesnt converge.

I tried putting count1 and count before and after the model and they are all counting 1000. But I know for sure that some of the models don't converge and give errors (thus if x1 categorical is such that it has only one level instead of two levels after resampling then we have errors).

Can someone help me how I can use tryCatch inside this while loop to be able to solve this problem?

1 Answer 1

1

You need something like this (and you need to increment your while loop):

i <- 1
count1 <- 0
fit <- rep(NA, 1000)

while(i <= 1000) { 
    dat <- sample(data, replace = T)
    temp <- try(lm(y~x1 + x2, data = dat))
    if(inherits(temp,"try-error"))
        count1 <- count1 + 1
    else
        fit[i] <- temp
    i <- i + 1
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.