In this lab, you’ll investigate the probability distribution that is most central to statistics: the normal distribution. If you are confident that your data are nearly normal, that opens the door to many powerful statistical methods. Here we’ll use the graphical tools of R to assess the normality of our data and also learn how to generate random numbers from a normal distribution.

Getting Started

Load packages

In this lab, we will explore and visualize the data using the tidyverse suite of packages as well as the openintro package.

Let’s load the packages.

rm(list=ls())
library(tidyverse)
library(openintro)

The data

This week you’ll be working with fast food data. This data set contains data on 515 menu items from some of the most popular fast food restaurants worldwide. Let’s take a quick peek at the first few rows of the data.

Either you can use glimpse like before, or head to do this.

library(tidyverse)
library(openintro)
data("fastfood", package='openintro')
head(fastfood)
## # A tibble: 6 x 17
##   restaurant item       calories cal_fat total_fat sat_fat trans_fat cholesterol
##   <chr>      <chr>         <dbl>   <dbl>     <dbl>   <dbl>     <dbl>       <dbl>
## 1 Mcdonalds  Artisan G~      380      60         7       2       0            95
## 2 Mcdonalds  Single Ba~      840     410        45      17       1.5         130
## 3 Mcdonalds  Double Ba~     1130     600        67      27       3           220
## 4 Mcdonalds  Grilled B~      750     280        31      10       0.5         155
## 5 Mcdonalds  Crispy Ba~      920     410        45      12       0.5         120
## 6 Mcdonalds  Big Mac         540     250        28      10       1            80
## # ... with 9 more variables: sodium <dbl>, total_carb <dbl>, fiber <dbl>,
## #   sugar <dbl>, protein <dbl>, vit_a <dbl>, vit_c <dbl>, calcium <dbl>,
## #   salad <chr>

You’ll see that for every observation there are 17 measurements, many of which are nutritional facts.

You’ll be focusing on just three columns to get started: restaurant, calories, calories from fat.

Let’s first focus on just products from McDonalds and Dairy Queen.

mcdonalds <- fastfood %>%
  filter(restaurant == "Mcdonalds")
dairy_queen <- fastfood %>%
  filter(restaurant == "Dairy Queen")
  1. Make a plot (or plots) to visualize the distributions of the amount of calories from fat of the options from these two restaurants. How do their centers, shapes, and spreads compare?

ANSWER

They both have somewhat similar shapes showing some “bell curve” characteristics. Yet they are not symmetrical with both having some right skewness, specially McDonalds with some product extending far to the right of the mean. It’s mean is very similar, but McDonalds just a little large.

We can confirm these results by taking the mean and standard devition of both distribution. McDonalds has a mean of 286 vs 260 for Dairy Queen. Standard Deviation of MCD is larger at 221 vs Dary Queen at 156.

# First distribution
hist(mcdonalds$cal_fat, breaks=10,col=rgb(1,0,0,0.5), xlab="Fat Calories", 
     ylab="# of Products", main="Distribution of Fat Calories of Products" )

# Second with add=T to plot on top
hist(dairy_queen$cal_fat, breaks=8,col=rgb(0,0,1,0.5), add=T)

# Add legend
legend("topright", legend=c("McDonalds","Dairy Queen"), col=c(rgb(1,0,0,0.5), 
     rgb(0,0,1,0.5)), pt.cex=2, pch=15 )

mcdonalds %>%
  summarise(mean = mean(cal_fat), SD=sd(cal_fat))
## # A tibble: 1 x 2
##    mean    SD
##   <dbl> <dbl>
## 1  286.  221.
dairy_queen %>%
  summarise(mean = mean(cal_fat), SD=sd(cal_fat))
## # A tibble: 1 x 2
##    mean    SD
##   <dbl> <dbl>
## 1  260.  156.

The normal distribution

In your description of the distributions, did you use words like bell-shapedor normal? It’s tempting to say so when faced with a unimodal symmetric distribution.

To see how accurate that description is, you can plot a normal distribution curve on top of a histogram to see how closely the data follow a normal distribution. This normal curve should have the same mean and standard deviation as the data. You’ll be focusing on calories from fat from Dairy Queen products, so let’s store them as a separate object and then calculate some statistics that will be referenced later.

dqmean <- mean(dairy_queen$cal_fat)
dqsd   <- sd(dairy_queen$cal_fat)

Next, you make a density histogram to use as the backdrop and use the lines function to overlay a normal probability curve. The difference between a frequency histogram and a density histogram is that while in a frequency histogram the heights of the bars add up to the total number of observations, in a density histogram the areas of the bars add up to 1. The area of each bar can be calculated as simply the height times the width of the bar. Using a density histogram allows us to properly overlay a normal distribution curve over the histogram since the curve is a normal probability density function that also has area under the curve of 1. Frequency and density histograms both display the same exact shape; they only differ in their y-axis. You can verify this by comparing the frequency histogram you constructed earlier and the density histogram created by the commands below.

ggplot(data = dairy_queen, aes(x = cal_fat)) +
        geom_blank() +
        geom_histogram(aes(y = ..density..)) +
        stat_function(fun = dnorm, args = c(mean = dqmean, sd = dqsd), col = "tomato")

After initializing a blank plot with geom_blank(), the ggplot2 package (within the tidyverse) allows us to add additional layers. The first layer is a density histogram. The second layer is a statistical function – the density of the normal curve, dnorm. We specify that we want the curve to have the same mean and standard deviation as the column of fat calories. The argument col simply sets the color for the line to be drawn. If we left it out, the line would be drawn in black.

  1. Based on the this plot, does it appear that the data follow a nearly normal distribution?

ANSWER The gaussian on top of the observed distribution shows more clearly the fat tail in the larger calorie products. While in a normal distribution tails are “thin”, this observed one is actually taller than and comparable to values closer to the mean.

Evaluating the normal distribution

Eyeballing the shape of the histogram is one way to determine if the data appear to be nearly normally distributed, but it can be frustrating to decide just how close the histogram is to the curve. An alternative approach involves constructing a normal probability plot, also called a normal Q-Q plot for “quantile-quantile”.

ggplot(data = dairy_queen, aes(sample = cal_fat)) + 
  geom_line(stat = "qq")

This time, you can use the geom_line() layer, while specifying that you will be creating a Q-Q plot with the stat argument. It’s important to note that here, instead of using x instead aes(), you need to use sample.

The x-axis values correspond to the quantiles of a theoretically normal curve with mean 0 and standard deviation 1 (i.e., the standard normal distribution). The y-axis values correspond to the quantiles of the original unstandardized sample data. However, even if we were to standardize the sample data values, the Q-Q plot would look identical. A data set that is nearly normal will result in a probability plot where the points closely follow a diagonal line. Any deviations from normality leads to deviations of these points from that line.

The plot for Dairy Queen’s calories from fat shows points that tend to follow the line but with some errant points towards the upper tail. You’re left with the same problem that we encountered with the histogram above: how close is close enough?

A useful way to address this question is to rephrase it as: what do probability plots look like for data that I know came from a normal distribution? We can answer this by simulating data from a normal distribution using rnorm.

set.seed(12345)
sim_norm <- rnorm(n = nrow(dairy_queen), mean = dqmean, sd = dqsd)

The first argument indicates how many numbers you’d like to generate, which we specify to be the same number of menu items in the dairy_queen data set using the nrow() function. The last two arguments determine the mean and standard deviation of the normal distribution from which the simulated sample will be generated. You can take a look at the shape of our simulated data set, sim_norm, as well as its normal probability plot.

  1. Make a normal probability plot of sim_norm. Do all of the points fall on the line? How does this plot compare to the probability plot for the real data? (Since sim_norm is not a data frame, it can be put directly into the sample argument and the data argument can be dropped.)

ANSWER

Short answer is no. There is randomness in the data generation from R thus normal noise is expected. Also the sample is very small so you can expect some noticeable variations vs the perfect bell curve.

df_sim_norm <- data.frame(sim_norm)
colnames(df_sim_norm) <- "cal_fat"
ggplot(data = df_sim_norm, aes(x = cal_fat)) +
        geom_blank() +
        geom_histogram(aes(y = ..density..)) +
        stat_function(fun = dnorm, args = c(mean = dqmean, sd = dqsd), col = "tomato")

Even better than comparing the original plot to a single plot generated from a normal distribution is to compare it to many more plots using the following function. It shows the Q-Q plot corresponding to the original data in the top left corner, and the Q-Q plots of 8 different simulated normal data. It may be helpful to click the zoom button in the plot window.

openintro::qqnormsim(sample = cal_fat, data = dairy_queen)

  1. Does the normal probability plot for the calories from fat look similar to the plots created for the simulated data? That is, do the plots provide evidence that the calories are nearly normal?

ANSWER While looking at many simulations we could conclude that on average the qq-plots of simulated data vs actual data show more of a nearly normal distribution.

  1. Using the same technique, determine whether or not the calories from McDonald’s menu appear to come from a normal distribution.

ANSWER With McDonalds is more difficult to conclude that it follows a normal distribution. The fat tail toward the larger values deviates from the straight line in the qqplot.

openintro::qqnormsim(sample = cal_fat, data = mcdonalds)

Normal probabilities

Okay, so now you have a slew of tools to judge whether or not a variable is normally distributed. Why should you care?

It turns out that statisticians know a lot about the normal distribution. Once you decide that a random variable is approximately normal, you can answer all sorts of questions about that variable related to probability. Take, for example, the question of, “What is the probability that a randomly chosen Dairy Queen product has more than 600 calories from fat?”

If we assume that the calories from fat from Dairy Queen’s menu are normally distributed (a very close approximation is also okay), we can find this probability by calculating a Z score and consulting a Z table (also called a normal probability table). In R, this is done in one step with the function pnorm().

1 - pnorm(q = 600, mean = dqmean, sd = dqsd)
## [1] 0.01501523

Note that the function pnorm() gives the area under the normal curve below a given value, q, with a given mean and standard deviation. Since we’re interested in the probability that a Dairy Queen item has more than 600 calories from fat, we have to take one minus that probability.

Assuming a normal distribution has allowed us to calculate a theoretical probability. If we want to calculate the probability empirically, we simply need to determine how many observations fall above 600 then divide this number by the total sample size.

dairy_queen %>% 
  filter(cal_fat > 600) %>%
  summarise(percent = n() / nrow(dairy_queen))
## # A tibble: 1 x 1
##   percent
##     <dbl>
## 1  0.0476

Although the probabilities are not exactly the same, they are reasonably close. The closer that your distribution is to being normal, the more accurate the theoretical probabilities will be.

  1. Write out two probability questions that you would like to answer about any of the restaurants in this dataset. Calculate those probabilities using both the theoretical normal distribution as well as the empirical distribution (four probabilities in all). Which one had a closer agreement between the two methods?

ANSWER

Question 1 If I pick a random product from each restaurant, what is the probability it would be between 200 and 400 calories?

First let’s calculate the parameters for McDonalds

mdmean <- mean(mcdonalds$cal_fat)
mdsd   <- sd(mcdonalds$cal_fat)

Let’s start with Dairy Queen Since we are looking for values betwen a and b, we would need two pnorm operations to get probability we are looking for.

#Theoretical
T200_400DQ <- pnorm(q = 400, mean = dqmean, sd = dqsd) - pnorm(q = 200, mean = dqmean, sd = dqsd)

#From data
D200_400DQ <- dairy_queen %>% 
  filter(cal_fat >= 200 & cal_fat <= 400) %>%
  summarise(percent = n() / nrow(dairy_queen))

T200_400DQ
## [1] 0.4641236
D200_400DQ
## # A tibble: 1 x 1
##   percent
##     <dbl>
## 1   0.357
T200_400DQ/D200_400DQ-1
##    percent
## 1 0.299546

Results showed a difference of around 30% between theoretical and actual data.

Now Let’s do McDonalds

#Theoretical
T200_400MD <- pnorm(q = 400, mean = mdmean, sd = mdsd) - pnorm(q = 200, mean = mdmean, sd = mdsd)

#From data
D200_400MD <- mcdonalds %>% 
  filter(cal_fat >= 200 & cal_fat <= 400) %>%
  summarise(percent = n() / nrow(mcdonalds))

T200_400MD
## [1] 0.3485409
D200_400MD
## # A tibble: 1 x 1
##   percent
##     <dbl>
## 1   0.474
T200_400MD/D200_400MD-1
##      percent
## 1 -0.2641913

The diffenrence observed for McDonalds was about 26%. I would say fairly similar to the 30% we observed for Dairy Queen.

Question 2 If I pick one product from each restaurant what is the probability it will be equal or less than 250 calories?

# Dairy Queen Firsts
#Theoretical
T250DQ <- pnorm(q = 250, mean = dqmean, sd = dqsd)

#From data
D250DQ <- dairy_queen %>% 
  filter(cal_fat <= 250) %>%
  summarise(percent = n() / nrow(dairy_queen))

T250DQ
## [1] 0.473312
D250DQ
## # A tibble: 1 x 1
##   percent
##     <dbl>
## 1   0.595
T250DQ/D250DQ-1
##      percent
## 1 -0.2048359
# Now let's do McDonalds
#Theoretical
T250MD <- pnorm(q = 250, mean = mdmean, sd = mdsd)

#From data
D250MD <- mcdonalds %>% 
  filter(cal_fat <= 250) %>%
  summarise(percent = n() / nrow(mcdonalds))

T250MD
## [1] 0.4359589
D250MD
## # A tibble: 1 x 1
##   percent
##     <dbl>
## 1   0.596
T250MD/D250MD-1
##      percent
## 1 -0.2691277

The difference between theoretical and actual for Dairy Queen was about 20%, while the comparison for McDonalds was about 26%


More Practice

  1. Now let’s consider some of the other variables in the dataset. Out of all the different restaurants, which ones’ distribution is the closest to normal for sodium?

ANSWER First lets check how many restaurants we have in the dataset

table(fastfood$restaurant)
## 
##       Arbys Burger King Chick Fil-A Dairy Queen   Mcdonalds       Sonic 
##          55          70          27          42          57          53 
##      Subway   Taco Bell 
##          96         115

We can now see we have 8 restaurants:

  • Arbys
  • Burger King
  • Chick Fill-A
  • Dairy Queen
  • Mc Donalds
  • Sonic
  • Subway
  • Taco Bell

Now let’s compare how their sodium distribution compare to a normal distribution

restaurants <- list("Arbys","Burger King","Chick Fil-A","Dairy Queen","Mcdonalds","Sonic","Subway","Taco Bell")

for (rest_list in restaurants) {
  restaurant <- filter(fastfood, restaurant == rest_list)
  qqnorm(restaurant$sodium, main = rest_list)
}

After looking at the above plots. I’d say visually Burger King seems to be the closest to a normal distribution

  1. Note that some of the normal probability plots for sodium distributions seem to have a stepwise pattern. why do you think this might be the case?

ANSWER

In general pronounced steps would indicate a concentration of values (multi-modal). If we plot their distribution we would be a able to see concentration of product farther away from ther mean. In the specific case where this step is at the high-end would indicate right-skewness or even fat tails, which is something we saw in McDonalds for example, but other restaurants also show.

  1. As you can see, normal probability plots can be used both to assess normality and visualize skewness. Make a normal probability plot for the total carbohydrates from a restaurant of your choice. Based on this normal probability plot, is this variable left skewed, symmetric, or right skewed? Use a histogram to confirm your findings.

ANSWER

Let’s pick Chick Fil-A

cfa <- fastfood %>%
  filter(restaurant == "Chick Fil-A")

cfmean = mean(cfa$total_carb)
cfsd = sd(cfa$total_carb)

ggplot(data = cfa, aes(x = total_carb)) +
        geom_blank() +
        geom_histogram(aes(y = ..density..)) +
        stat_function(fun = dnorm, args = c(mean = cfmean, sd = cfsd), col = "tomato")

I would say that Chick Fil-A shows right skewness, which some high peak on the lower number. In fact the left (lower) peak was higher than the theoretical mean of the restaurant.