rdistributiongamma-distribution

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


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?


Solution

  • You could try to quickly fit Gamma distribution. Being two-parameters distribution one could recover them by finding sample mean and variance. Here you could have some samples to be negative as soon as mean is positive.

    set.seed(31234)
    x <- rgamma(100, 2.0, 11.0) + rnorm(100, 0, .01) #gamma distr + some gaussian noise
    #print(x)
    
    m <- mean(x)
    v <- var(x)
    
    print(m)
    print(v)
    
    scale <- v/m
    shape <- m*m/v
    
    print(shape)
    print(1.0/scale)
    

    For me it prints

    > print(shape)
    [1] 2.066785
    > print(1.0/scale)
    [1] 11.57765
    >