Gamma distribution in R, This guide demonstrates how to use R to fit a gamma distribution to a dataset.

## Gamma Distribution Fitting in R

Let’s say you have a dataset z that was produced using the following method:

Create 30 random values that are distributed according to a gamma distribution with shape parameters of 4 and 9 along with some gaussian noise.

Gama <- rgamma(30, 4, 9) + rnorm(30, 0, .03)

Now we can view the first 6 values

head(Gama) [1] 0.1362240 0.5979568 0.4930604 0.2808689 0.4361617

With the help of the fitdistrplus package in R, we can examine how well a gamma distribution fits this dataset Gama.

if not already installed, install the ‘fitdistrplus’ package.

install.packages('fitdistrplus')

Yes, now we can load the package

library(fitdistrplus)

To fit a distribution using this package, the following general syntax should be used:

fitdist(dataset, distr = “your distribution choice”, method = “your method of fitting the data”)

In this instance, we’ll use the gamma distribution and maximum likelihood estimation approach to suit the dataset z that we created earlier:

Using mle, we fitted our dataset to a gamma distribution.

fit <- fitdist(Gama, distr = "gamma", method = "mle")

Let’s view the summary of the fit

summary(fit)

Fitting of the distribution ‘ gamma ‘ by maximum likelihood

Parameters : estimate Std. Error shape 3.551416 0.647940 rate 7.019582 1.375659 Loglikelihood: -0.1783264 AIC: 4.356653 BIC: 8.371319 Correlation matrix: shape rate shape 1.0000000 0.9309661 rate 0.9309661 1.0000000

The following syntax can then be used to create several charts that demonstrate how well the gamma distribution fits the dataset.

par(mar=c(1, 1, 1, 1)) plot(fit)

**Further Resources**:-

The following tutorials provide guidance on using R to manipulate various probability distributions:

The Multinomial Distribution in R – Data Science Tutorials

The Uniform Distribution in R – Data Science Tutorials

Test for Normal Distribution in R-Quick Guide – Data Science Tutorials