library(ggfortify)
ggdistribution(dgamma, seq(0, 50, 0.1), rate=1/4, shape=5)
We discussed the exponential distribution:
The gamma distribution is similar - but more general.
Wait times at a snack bar are in the data set Service.
Load this data set and plot a histogram.
library(resampledata)
hist(Service$Times, prob=T)
Plot a gamma distribution on the same plot with:
hist(Service$Times, prob=T)
curve(dgamma(x, shape=10, rate=10), add=TRUE)
Experiment with the parameters a little and see if you can get the gamma distribution to match the distribution of the sample data (histogram).
We'll use a method called the Method of Moments to determine the parameters to use.
Read the first part of section 6.2.
A few hints:
\[ \begin{align*} \Gamma(r)&=\int_0^\infty x^{r-1}e^{- x} dx \\ f(x,r,\lambda)&=\frac{1}{\Gamma(r)}\lambda^rx^{r-1}e^{-\lambda x} \end{align*} \]
\[ \begin{align*} E[X]&=\int_0^\infty x f(x,r,\lambda) dx\\ &= \int_0^\infty x \frac{1}{\Gamma(r)}\lambda^rx^{r-1}e^{-\lambda x} dx\\ &=\frac{\lambda^r}{\Gamma(r)}\int_0^\infty x^r e^{-\lambda x} dx && w=\lambda x, dw=\lambda dx\\ &=\frac{\lambda^{r-1}}{\Gamma(r)}\int_0^\infty \left(\frac{w}{\lambda}\right)^r e^{-w} dw \\ &=\frac{1}{\lambda \Gamma(r)} \int_0^\infty w^r e^{-w} dw && u=w^r, dv=e^{-w}dw\\ & && du = r w^{r-1} dw, v= -e^{-w}\\ \end{align*} \]
\[ \begin{align*} E[X]&=\\ &=\frac{1}{\lambda \Gamma(r)}\left[-w^re^{-w} \biggr|_0^\infty+r\int_0^\infty w^{r-1}e^{-w} dw \right]\\ &=\frac{1}{\lambda \Gamma(r)}\left[0+r\Gamma(r) \right]\\ &=\frac{r}{\lambda} \end{align*} \]
You could compute these with a loop, but R's vector structure provides an elegant way to compute the right hand side.
Here's an example. Say my \( X_i \) s are:
Xs <- c(12, 14, 17, 2, 3, 19, 7, 12)
(I just made them up.)
To compute \[ \sum_{i=1}^n X_i^3 \] I will cube each of the \( X_i \) s and then add them together.
Xs^3
[1] 1728 2744 4913 8 27 6859 343 1728
sum(Xs^3)
[1] 18350
All that's left to do is divide by \( n \).