can.u - 1 year ago 78

R Question

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:

So how can skip this error?

Here is the file to be uploaded : http://www.filedropper.com/samplest

Here is the code:

`library(fitdistrplus)`

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.data.frame(lapply(importeddata, 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

suppressMessages(aa)

print(aa)

}

Answer Source

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`

for

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