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 #calculate gamma density for each x-value
y #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 #calculate gamma density for each x-value
y #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 #calculate gamma density for each x-value
y #create quantile plot
plot(y)
Example 4: How to Use rgamma()
The following code shows how to use the rgamma() function to generate and visualize 1,000 random variables that follow a gamma distribution with a shape parameter of 5 and a rate parameter of 3:
#make this example reproducible set.seed(0) #generate 1,000 random values that follow gamma distribution x #create histogram to view distribution of values hist(x)
Additional Resources
The following tutorials explain how to use other common statistical distributions in R:
How to Use the Normal Distribution in R
How to Use the Binomial Distribution in R
How to Use the Poisson Distribution in R
How to Use the Geometric Distribution in R