How to use the Gamma Distribution in R (With Examples)

The gamma distribution in R can be used to calculate probabilities for a variety of statistical models. To use the gamma distribution in R, you must specify the parameters of the distribution such as the shape, rate, and scale. After the parameters have been specified, the dgamma and pgamma functions can be used to calculate the density and cumulative probability of the gamma distribution, respectively. Examples of how to use the gamma distribution in R can be found in the R documentation.


In statistics, the gamma distribution is often used to model probabilities related to waiting times.

We can use the following functions to work with the gamma distribution in R:

  • dgamma(x, shape, rate) – finds the value of the density function of a gamma distribution with certain shape and rate parameters.
  • pgamma(q, shape, rate) – finds the value of the cumulative density function of a gamma distribution with certain shape and rate parameters.
  • qgamma(p, shape, rate) – finds the value of the inverse cumulative density function of a gamma distribution with certain shape and rate parameters.
  • rgamma(n, shape, rate) – generates n random variables that follow a gamma distribution with certain shape and rate parameters.

The following examples show how to use each of these functions in practice.

Example 1: How to Use dgamma()

The following code shows how to use the dgamma() function to create a probability density plot of a gamma distribution with certain parameters:

#define x-values
x <- seq(0, 2, by=0.01)   
  
#calculate gamma density for each x-value
y <- dgamma(x, shape=5) 
  
#create density plot
plot(y)

Example 2: How to Use pgamma()

The following code shows how to use the pgamma() function to create a cumulative density plot of a gamma distribution with certain parameters:

#define x-values
x <- seq(0, 2, by=0.01)   
  
#calculate gamma density for each x-value
y <- pgamma(x, shape=5) 
  
#create cumulative density plot
plot(y)

Example 3: How to Use qgamma()

The following code shows how to use the qgamma() function to create a quantile plot of a gamma distribution with certain parameters:

#define x-values
x <- seq(0, 1, by=0.01)   
  
#calculate gamma density for each x-value
y <- qgamma(x, shape=5) 
  
#create quantile plot
plot(y)

Example 4: How to Use rgamma()

#make this example reproducible
set.seed(0)

#generate 1,000 random values that follow gamma distribution
x <- rgamma(n=1000, shape=5, rate=3)

#create histogram to view distribution of values
hist(x)

The following tutorials explain how to use other common statistical distributions in R:

x