Solved – Why does fitdistr does not work with gamma

datasetdensity functiongamma distributionr

I am tring to find a probability density for some waiting time, but I am having a hard time. Fitdistr does not work with Gamma. Am I missing something?

Is there another density that fits better to this?

library(MASS) 

wt = read.csv("http://isgeek.eu/SITN/waitingTime.csv", sep="\t", header = TRUE)
hist(wt$x, prob=TRUE)

# Estimate an exp proba
paraw <- fitdistr(wt$x,densfun="exponential")
curve(dexp(x, paraw$estimate[1]), 0,1300, add=TRUE, col="blue")
ks.test(wt$x, "pexp", paraw$estimate[1]) 

# Estimate a weilbull proba
paraw <- fitdistr(wt$x[wt$x!=0],densfun="weibull")
curve(dweibull(x, paraw$estimate[1], paraw$estimate[2]), 0,4000, add=TRUE, col="blue")
ks.test(wt$x, "pweibull", paraw$estimate[1], paraw$estimate[2]) 

# Estimate a gamma proba
paraw <- fitdistr(wt$x,densfun="gamma", list(shape = 1, rate = 0.1), lower = 40)
# this does not work...

Best Answer

per comments: it seems to work when you take out the 0's (see red curve below). Also you may consider adjusting the "lower" parameter to a decimal or an interval.

#changed "lower" parameter 
paraw <- fitdistr(wt$x[wt$x!=0], densfun="gamma", list(shape = 1, rate = 0.1), 
                  lower = 0.4)
curve(dgamma(x, paraw$estimate[1], paraw$estimate[2]), 0,4000, add=TRUE, 
      col="red")
ks.test(wt$x, "pgamma", paraw$estimate[1], paraw$estimate[2]) 

# One-sample Kolmogorov-Smirnov test
# 
# data:  wt$x
# D = 0.4372, p-value < 2.2e-16
# alternative hypothesis: two-sided


# default: maybe a good estimate
paraw <- fitdistr(wt$x[wt$x!=0], densfun="gamma")
curve(dgamma(x, paraw$estimate[1], paraw$estimate[2]), 0,4000, add=TRUE, 
      col="gray")
ks.test(wt$x, "pgamma", paraw$estimate[1], paraw$estimate[2]) 

# One-sample Kolmogorov-Smirnov test
# 
# data:  wt$x
# D = 0.0351, p-value = 0.1633
# alternative hypothesis: two-sided

gamma2

Related Question