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.
library(tidyverse)
library(openintro)
library(psych)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.
data("fastfood", package='openintro')
head(fastfood)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")- 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?
bind_rows(mcdonalds,dairy_queen) %>%
select(restaurant, cal_fat) %>%
ggplot(
mapping = aes(x=cal_fat, fill=restaurant)
) +
geom_density(
alpha=.5,
color="white"
) +
labs(title="McDonalds and Dairy Queen Cal_Fat Distributions Similar")bind_rows(mcdonalds,dairy_queen) %>%
select(restaurant, cal_fat) %>%
ggplot(
mapping = aes(x=cal_fat, fill=restaurant)
) +
geom_boxplot(
outlier.color="purple"
) +
labs(title="McDonalds and Dairy Queen Cal_Fat Distributions Similar")describe(mcdonalds$cal_fat)describe(dairy_queen$cal_fat)From the above graphs, we see that the general distributions for cal_fat at both McDonalds and Dairy Queen are very alike. Both are bell-shaped and skewed to the right. However, some notable takeaways include:
- Mcdonalds has a higher mean and median
- McDonalds has a higher variance
- Mcdonalds has a greater number of outliers, which explains the discrepancy between max values for the two restaurants (670 cals vs 1270)
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.
- Based on the this plot, does it appear that the data follow a nearly normal distribution?
Answer: Based on the graphs above, it does look like the dairy_queen cal_fat distribution is “close to” normal. However the quantity of higher values, which should only make a small percent of the overall data (if normal), are a concern. This is additionally evidence in the below Normal QQplot.
qqnorm(dairy_queen$cal_fat)
qqline(dairy_queen$cal_fat, col = "purple")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.
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.
data.frame(sim_norm) %>%
ggplot() +
geom_density(mapping=aes(x=sim_norm))data.frame(sim_norm) %>%
ggplot(mapping=aes(sample=sim_norm)) +
geom_line(stat="qq")- 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? (Sincesim_normis not a data frame, it can be put directly into thesampleargument and thedataargument can be dropped.)
Answer: Most of the points fall on the diagonal, but there is some minor variation in the center of the line.
data.frame(sim_norm) %>%
ggplot(mapping=aes(sample=sim_norm)) +
geom_line(stat="qq")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)- 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: For the most part all of the plots, cal_fat as well as the generated distributions, look similar. That is to say, cal_fat is nearly normal.
The most noticeable difference is that there is a “break” in cal_fat at around 1 on the x-axis. While there is deviation among the other simulated plots, none exhibit this type of behavior.
- Using the same technique, determine whether or not the calories from McDonald’s menu appear to come from a normal distribution.
Answer: When comparing mcdonalds cal_fat qqplot against the simulations, it is clear that there is a meaningful difference which was not seen in the above dairy_queen example. As we observed earlier, the mcdonalds cal_fat distribution is nearly normal at the left tail and to the center. However, at the right tail end, there is significant deviation from a theoretical normal distribution.
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))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.
- 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?
QUESTION 1
What is the probability that a menu item’s total_carb value is less than 30 at Taco Bell?
fastfood %>%
filter(restaurant == "Taco Bell") %>%
ggplot(mapping=aes(x=total_carb))+
geom_histogram(binwidth=5)tacobell <- fastfood %>%
filter(restaurant=="Taco Bell")
taco_mean <- mean(tacobell$total_carb)
taco_sd <- sd(tacobell$total_carb)using pnorm()
pnorm(30,taco_mean,taco_sd)## [1] 0.2300381
empirical
tacobell %>%
filter(total_carb < 30) %>%
summarize(
percent = n() / nrow(tacobell)
)QUESTION 2
What is the probability that any item from any of the restaurants included in the fastfood dataset has a sodium value above 1500?
fastfood %>%
ggplot(mapping=aes(x=sodium))+
geom_histogram(binwidth=30) ### using Pnorm
sodium_mean <- mean(fastfood$sodium)
sodium_sd <- sd(fastfood$sodium)
p_gt_1500 = 1-pnorm(1500,mean=sodium_mean,sd=sodium_sd)
p_gt_1500## [1] 0.3567831
Emprical
fastfood %>%
filter(sodium > 1500) %>%
summarize(
percent = n() / nrow(fastfood)
)Out of the two questions, the first one had a smaller difference between the normal estimation versus the empirical one.
First Example Differences (pnorm() prob - emprical prob)
.230-.261 = -.031
Second Example Differences (pnorm() prob - emprical prob)
.3567-.2815 = .0772
More Practice
- 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:
Based on the below QQ plots, it appears that Burger King’s sodium distribution is the closest to normal.
fastfood %>%
ggplot() +
geom_point(mapping=aes(sample=sodium),
stat="qq") +
facet_wrap(~restaurant)- 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:
This is likely due to the fact that sodium values are discrete and in many cases repeat. We are plotting against the normal distribution which is continuous, so we can expect some “steps”.
- 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:
Based on the QQ-plot below, we see that Sonic total_carb distribution is right-skewed. This is evidenced by the fact that points on the right side of the graph do not fall onto the “diagonal line”
fastfood %>%
filter(restaurant == "Sonic") %>%
ggplot(mapping=aes(sample=total_carb)) +
geom_point(stat="qq")sonic <- fastfood %>%
filter(restaurant=="Sonic")
sonic_mean <- mean(sonic$sodium)
sonic_sd <- sd(sonic$sodium)sonic %>%
ggplot() +
geom_histogram(mapping=aes(x=sodium, y=..density..),
binwidth = 60) +
stat_function(fun = dnorm, args = c(mean = sonic_mean, sd = sonic_sd),
col = "tomato")