Lab 4: The Normal Distribution

Load Packages

library(tidyverse)
## ── Attaching packages ───────────────────────────────────────────────────────────────────────────────────────────────────────────────── tidyverse 1.3.0 ──
## ✓ ggplot2 3.3.2     ✓ purrr   0.3.4
## ✓ tibble  3.0.3     ✓ dplyr   1.0.2
## ✓ tidyr   1.1.2     ✓ stringr 1.4.0
## ✓ readr   1.3.1     ✓ forcats 0.5.0
## ── Conflicts ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────── tidyverse_conflicts() ──
## x dplyr::filter() masks stats::filter()
## x dplyr::lag()    masks stats::lag()
library(openintro)
## Loading required package: airports
## Loading required package: cherryblossom
## Loading required package: usdata

The 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.

Use glimpse or head to do this.

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  Arti…      380      60         7       2       0            95
## 2 Mcdonalds  Sing…      840     410        45      17       1.5         130
## 3 Mcdonalds  Doub…     1130     600        67      27       3           220
## 4 Mcdonalds  Gril…      750     280        31      10       0.5         155
## 5 Mcdonalds  Cris…      920     410        45      12       0.5         120
## 6 Mcdonalds  Big …      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")

Exercise 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?

hist(mcdonalds$cal_fat, main="McDonald's Calories from Fat", xlab = "Calories from Fat")

hist(dairy_queen$cal_fat, main="Dairy Queen Calories from Fat", xlab = "Calories from Fat")

McDonald’s calories from fat distribution is strongly right-skewed. Dairy Queen’s is more “normal,” but still has a right skew. McDonald’s has a wider spread (from 0 to 1400 calories), while Dairy Queen’s ranges from 0 to 700.

The Normal Distribution

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")
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

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 calories from fat. 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.

Exercise 2

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

It is still difficult to tell if this is a normal distribution. The density histogram is definitely higher at the left end and increasing in relation to the normal curve.

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 inside 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.

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.

Exercise 3

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 dataframe, it can be put directly into the sample argument and the data argument can be dropped.)

ggplot(mapping = aes(sample = sim_norm))+
  geom_line(stat='qq')

In this qq plot of simulated data, not all of the points fall on a line. It looks roughly similar to the plot of dairy queen data above, though the dairy queen plot varies more from a line at the tails.

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.

qqnormsim(sample = cal_fat, data = dairy_queen)

Exercise 4

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 from fat are nearly normal?

This sampling of qq plots compared to the data from dairy queen make the dairy queen data look much more normal. In comparison to the other plots, with the exception of the far right tail, the plots are similar.

Exercise 5

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

# Get the mean and standard deviation of the McDonald's data

mcdmean <- mean(mcdonalds$cal_fat)
mcdsd   <- sd(mcdonalds$cal_fat)
# Plot density histogram and normal curve

ggplot(data = mcdonalds, aes(x = cal_fat)) +
        geom_blank() +
        geom_histogram(aes(y = ..density..)) +
        stat_function(fun = dnorm, args = c(mean = mcdmean, sd = mcdsd), col = "tomato")
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

# Generate Q-Q Plot

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

# Simulate normal data

sim_norm2 <- rnorm(n = nrow(mcdonalds), mean = mcdmean, sd = mcdsd)
# Create QQ Plot of simulated data
ggplot(mapping = aes(sample = sim_norm2))+
  geom_line(stat='qq')

# Create multiple plots of simulated data alongside sample data

qqnormsim(sample = cal_fat, data = mcdonalds)

The McDonald’s sample has a much more skewed right tail than the simulation data.

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 (5% vs 2%). The closer that your distribution is to being normal, the more accurate the theoretical probabilities will be.

Exercise 6

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?

  1. What is the probability a randomly chosen product from McDonald’s has more than 600 calories from fat?
# Theoretical normal distribution

1 - pnorm(q = 600, mean = mcdmean, sd = mcdsd)
## [1] 0.07733771
# Empirical answer

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

There is a theoretical 8% probability and an empirical 7% probability that a randomly selected item at McDonald’s has over 600 calories from fat.

  1. What is the probability a randomly chosen product from McDonald’s has fewer than 200 calories from fat?
# Theoretical normal distribution

pnorm(q = 200, mean = mcdmean, sd= mcdsd)
## [1] 0.349167
# Empirical answer

mcdonalds %>% 
  filter(cal_fat < 200) %>%
  summarise(percent = n() / nrow(mcdonalds))
## # A tibble: 1 x 1
##   percent
##     <dbl>
## 1   0.368

There is a 35% theoretical probability and 37% empirical probability that a randomly selected item at McDonald’s has fewer than 200 calories from fat.

Exercise 7

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?

# Identify which restaurants are in the dataset

unique(fastfood$restaurant)
## [1] "Mcdonalds"   "Chick Fil-A" "Sonic"       "Arbys"       "Burger King"
## [6] "Dairy Queen" "Subway"      "Taco Bell"

There are 8 unique restaurants. We need to make a datset for each.

hatechicken <- fastfood %>%
  filter(restaurant == "Chick Fil-A")
sonic <- fastfood %>%
  filter(restaurant == "Sonic")
arbys <- fastfood %>%
  filter(restaurant == "Arbys")
bk <- fastfood %>%
  filter(restaurant == "Burger King")
subway <- fastfood %>%
  filter(restaurant == "Subway")
taco <- fastfood %>%
  filter(restaurant == "Taco Bell")

Now we need to plot their sodium histograms.

hist(mcdonalds$sodium)

hist(dairy_queen$sodium)

hist(hatechicken$sodium)

hist(sonic$sodium)

hist(arbys$sodium)

hist(bk$sodium)

hist(subway$sodium)

hist(taco$sodium)

We’re just looking for the one that is closest to normal, so we don’t need to do qq plots for all of them, just those that look most normally distributed.

I’m going to do ones for Arby’s and Burger King.

First I will get the mean and standard deviation for both restaurants.

arbmean = mean(arbys$sodium)
arbsd = sd(arbys$sodium)

bkmean = mean(bk$sodium)
bksd = sd(bk$sodium)

Now I’ll do the fancy overlay plot for each.

ggplot(data = arbys, aes(x = sodium)) +
        geom_blank() +
        geom_histogram(aes(y = ..density..)) +
        stat_function(fun = dnorm, args = c(mean = arbmean, sd = arbsd), col = "blue")
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

ggplot(data = bk, aes(x = sodium)) +
        geom_blank() +
        geom_histogram(aes(y = ..density..)) +
        stat_function(fun = dnorm, args = c(mean = bkmean, sd = bksd), col = "orange")
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

It’s hard to tell which one is more normal, so I’ll do the qq plots.

# Generate Q-Q Plot

ggplot(data = arbys, aes(sample = sodium)) + 
  geom_line(stat = "qq")

# Generate Q-Q Plot

ggplot(data = bk, aes(sample = sodium)) + 
  geom_line(stat = "qq")

With these qq plots, they both look fairly normal. If forced to choose one, I would say the burger king sodium distribution is the most normal distribution of all the fast food restaurants.

Exercise 8

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?

I think this question indicates that despite being able to answer the previous question with histograms for most, the authors want me to make a qq plot for all the restaurants. So I’ll do that now.

# Create means for all restaurants

mcdsodiumean <- mean(mcdonalds$sodium)
dqsodiummean <- mean(dairy_queen$sodium)
hcmean <- mean(hatechicken$sodium)
sonicmean <- mean(sonic$sodium)
tacomean <- mean(taco$sodium)
subwaymean <- mean(subway$sodium)

# Create sd for all restaurants

mcdsodiumsd <- sd(mcdonalds$sodium)
dqsodiumsd <- sd(dairy_queen$sodium)
hcsd <- sd(hatechicken$sodium)
sonicsd <- sd(sonic$sodium)
tacosd <- sd(taco$sodium)
subwaysd <- sd(subway$sodium)

Oops. I didn’t need to do that for a simple QQ plot. Oh well.

# Generate Q-Q Plot

ggplot(data = mcdonalds, aes(sample = sodium)) + 
  geom_line(stat = "qq")

# Generate Q-Q Plot

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

# Generate Q-Q Plot

ggplot(data = hatechicken, aes(sample = sodium)) + 
  geom_line(stat = "qq")

# Generate Q-Q Plot

ggplot(data = sonic, aes(sample = sodium)) + 
  geom_line(stat = "qq")

# Generate Q-Q Plot

ggplot(data = taco, aes(sample = sodium)) + 
  geom_line(stat = "qq")

# Generate Q-Q Plot

ggplot(data = subway, aes(sample = sodium)) + 
  geom_line(stat = "qq")

There may be a stepwise element to these plots because some items are very high in sodium while others are not.

Exercise 9

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.

# Carbohydrate QQ plot for Subway

ggplot(data = subway, aes(sample = total_carb)) + 
  geom_line(stat = "qq")

Now THAT’S a step wise plot!

This variable appears to be very right skewed.

# histogram for subway carbs

ggplot(subway, aes(total_carb))+
  geom_histogram(binwidth = 5)

This is definitely a right-skewed distribution.