can.u can.u - 3 months ago 18
R Question

How can I prevent error in order to complete the loop?

I am trying to fit the best distribution for three variables which are gathered via .csv file. I tried to evaluate with provided distributions in r.
Then I will select the smallest one as a best fitted distribution. However, I cannot complete the loop because some errors can be occured when distributions are not able to be fitted for data.

for instance; beta distribution:

Error in fitdistr(xx1[, k], distributions[i]) : 'start' must be a named list

So how can skip this error?

Here is the file to be uploaded :

Here is the code:


importeddata <- read.csv(file.choose(), sep=";",na.strings = "", stringsAsFactors=FALSE, header = TRUE)

for(i in 1:tail(ncol(importeddata))){
importeddata[,i] <- gsub(",", ".", importeddata[ , i])}

xx1<- as.matrix(, as.numeric)))

distributions <- c("beta", "cauchy", "chi-squared", "exponential", "f", "gamma", "geometric", "log-normal", "lognormal", "logistic", "negative binomial", "normal", "Poisson", "t", "weibull")

for(k in 1:ncol(xx1))
for(i in 1:length(distributions))
aa <- fitdistr(xx1[,k], distributions[i])$loglik


If you just want to skip some code when the error occurs you can use the try() function. Everything that is inside the function won't break the code when an error occurs.

In your example, just substitue:

aa <- fitdistr(xx1[,k], distributions[i])$loglik


try({aa <- fitdistr(xx1[,k], distributions[i])$loglik})