How would you fit a gamma distribution to a data in R?

user1172468 picture user1172468 · Aug 6, 2017 · Viewed 18.8k times · Source

Suppose I have the variable x that was generated using the following approach:

x <- rgamma(100,2,11) + rnorm(100,0,.01) #gamma distr + some gaussian noise

    head(x,20)
 [1] 0.35135058 0.12784251 0.23770365 0.13095612 0.18796901 0.18251968
 [7] 0.20506117 0.25298286 0.11888596 0.07953969 0.09763770 0.28698417
[13] 0.07647302 0.17489578 0.02594517 0.14016041 0.04102864 0.13677059
[19] 0.18963015 0.23626828

How could I fit a gamma distribution to it?

Answer

Edgar Santos picture Edgar Santos · Aug 6, 2017

A good alternative is the fitdistrplus package by ML Delignette-Muller et al. For instance, generating data using your approach:

set.seed(2017)
x <- rgamma(100,2,11) + rnorm(100,0,.01)
library(fitdistrplus)
fit.gamma <- fitdist(x, distr = "gamma", method = "mle")
summary(fit.gamma)

Fitting of the distribution ' gamma ' by maximum likelihood 
Parameters : 
       estimate Std. Error
shape  2.185415  0.2885935
rate  12.850432  1.9066390
Loglikelihood:  91.41958   AIC:  -178.8392   BIC:  -173.6288 
Correlation matrix:
          shape      rate
shape 1.0000000 0.8900242
rate  0.8900242 1.0000000


plot(fit.gamma)

enter image description here