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.
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)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 × 17
## restaur…¹ item calor…² cal_fat total…³ sat_fat trans…⁴ chole…⁵ sodium total…⁶
## <chr> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 Mcdonalds Arti… 380 60 7 2 0 95 1110 44
## 2 Mcdonalds Sing… 840 410 45 17 1.5 130 1580 62
## 3 Mcdonalds Doub… 1130 600 67 27 3 220 1920 63
## 4 Mcdonalds Gril… 750 280 31 10 0.5 155 1940 62
## 5 Mcdonalds Cris… 920 410 45 12 0.5 120 1980 81
## 6 Mcdonalds Big … 540 250 28 10 1 80 950 46
## # … with 7 more variables: fiber <dbl>, sugar <dbl>, protein <dbl>,
## # vit_a <dbl>, vit_c <dbl>, calcium <dbl>, salad <chr>, and abbreviated
## # variable names ¹restaurant, ²calories, ³total_fat, ⁴trans_fat,
## # ⁵cholesterol, ⁶total_carb
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")Answer:
In order to visualize the distribution of these two restaurants. We can actually make a density plot for both on same graph and same axis which will give us an idea about how the calories are distributed against each other. We will be using ggplot with multi-layers in order to plot the data for both restaurants and we can also use geom_vline() function to find the center of both distribution using mean() function
colors <- c("Mcdonald" = "red", "Dairy Queen" = "green")
ggplot()+
geom_density(data=mcdonalds, aes(x=cal_fat,color="Mcdonald"), fill="red", alpha=.8)+
geom_vline(data = mcdonalds,aes(xintercept=mean(cal_fat)), color="red")+
geom_density(data=dairy_queen, aes(x=cal_fat,color="Dairy Queen"), fill="green", alpha=.6)+
geom_vline(data = dairy_queen,aes(xintercept=mean(cal_fat)), color="green")+
labs(x="Calories", y="Density", color="Restaurants")+
scale_color_manual(values = colors)+
annotate("text", x=270, y=.003, label="Mcdonald", angle=90,size=2,color="red")+
annotate("text", x=240, y=.0033, label="Dairy Queen", angle=90,size=2, color="black")+
theme_bw()In the graph above, the curve in green represents Dairy Queen while the curve in red represents Mcdonald. Calories are plotted on X-Axis while density of calories are plotted on Y-Axis. If we look at the overall distribution it looks like a normal or bell-shaped distribution and both curves are pretty much similar till the calories are around 700 mark but after that the graph shows that Mcdonald has some options available with higher calories from fat while Dairy queen does not and that is why Mcdonald has a larger spread. Similarly, the center point for Mcdonald is shifted towards right represented by vertical red line around 285.1 while Dairy Queen has its vertical line to the left of Mcdonald. The means can also be confirmed from summary() function with mean)() as below:
summary(mean(mcdonalds$cal_fat))## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 285.6 285.6 285.6 285.6 285.6 285.6
summary(mean(dairy_queen$cal_fat))## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 260.5 260.5 260.5 260.5 260.5 260.5
In your description of the distributions, did you use words like bell-shaped or 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.
Answer:
Yes it does, even though the graph does not follow a perfect bell shape and has some skewness to the right but it mimics 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.
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:
qqnorm(sim_norm)
qqline(sim_norm)We can see that not all the points falls on the diagonal line . The points scatters away at the both ends of line. And it is hard to tell if the plot is similar to the real one, since real data probability plot follows along the diagonal line in the mid section but there is deviation at the far ends of line which kind of questions the normality. This can be confirmed by creating a qq plot with a diagonal line for the real data as the graph shows below
qqnorm(dairy_queen$cal_fat)
qqline(dairy_queen$cal_fat)Now comparing this plot to the sim_norm we can see that
both plot follows the diagonal line closely at the mid section but
strays away at the end which kind of point towards long 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)Answer:
By just looking at the graph in the current condition the real data graph does look like the simulated ones. Adding to that since the points strays away at both (previous answer) kind of questions the normality of data. Coming to evidence so we will have carry out normality test (like Shapiro-Wilk’s method) to be fully convinced.
qqnormsim(sample = cal_fat, data = mcdonalds)The calories on Mcdonald’s menu looks different than the simulated one in comparison with Dairy Queen which looked more normalized while Mcdonald’s data does not seem to be in normal distribution but rather skewed towards right. Adding to that this can be confirmed by plotting a histogram as shown below:
hist(mcdonalds$cal_fat)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 × 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.
Answer: Question 1: What is the probability that a randomly chosen product from any of these fast food restaurants is less than 400 calories?
ff_mean <- mean(fastfood$calories)
ff_sd <- sd(fastfood$calories)
pnorm(q = 400, mean = ff_mean, sd = ff_sd)## [1] 0.3214986
fastfood %>%
filter(calories < 400) %>%
summarise(percent = n() / nrow(fastfood))## # A tibble: 1 × 1
## percent
## <dbl>
## 1 0.359
Over here we can see that the theoretical and empirical probability are relatively close to each other, which implies that the distribution is closer to normal.
Question 2: What is the probability that a randomly chosen Mcdonald’s product has more than 30g’s of protein?
a_mean <- mean(mcdonalds$protein)
a_sd <- sd(mcdonalds$protein)
1 - pnorm(q = 30, mean = a_mean, sd = a_sd)## [1] 0.6365819
mcdonalds %>%
filter(protein > 30) %>%
summarise(percent = n() / nrow(mcdonalds))## # A tibble: 1 × 1
## percent
## <dbl>
## 1 0.632
Again the theoretical and empirical probabilities are closer to each other.
Answer:
In order to find that out we will have to do a probability plot for each restaurant and visually which plot is more close to the normal distribution.
For Arby’s:
arbys <- fastfood %>%
filter(restaurant == "Arbys")
qqnorm(arbys$sodium, main = "Arbys")
qqline(arbys$sodium)For burger king:
burger_k <- fastfood %>%
filter(restaurant == "Burger King")
qqnorm(burger_k$sodium, main = "Burger King")
qqline(burger_k$sodium)For Chick Fil-A:
chick_fa <- fastfood %>%
filter(restaurant == "Chick Fil-A")
qqnorm(chick_fa$sodium, main = "Chick Fil-A")
qqline(chick_fa$sodium)For Mcdonald:
mcd <- fastfood %>%
filter(restaurant == "Mcdonalds")
qqnorm(mcd$sodium, main = "McDonald's")
qqline(mcd$sodium)For Dairy Queen:
dq <- fastfood %>%
filter(restaurant == "Dairy Queen")
qqnorm(dq$sodium, main = "Dairy Queen")
qqline(dq$sodium)For Sonic:
s <- fastfood %>%
filter(restaurant == "Sonic")
qqnorm(s$sodium, main = "Sonic")
qqline(s$sodium)For Subway:
sw <- fastfood %>%
filter(restaurant == "Subway")
qqnorm(sw$sodium, main = "Subway")
qqline(sw$sodium)For Taco bell:
tb <- fastfood %>%
filter(restaurant == "Taco Bell")
qqnorm(tb$sodium, main = "Taco Bell")
qqline(tb$sodium)Out of all the plots above Burger king and Chick Fil-A looks more close to normal distribution as compared to other restaurants.
Answer:
The reason could be that since different all the above restaurants have different options on their menu list like Fries, sandwiches, ice cream and salads etc and all of these can have different level of sodium in it. For example the sodium content in fries and sandwiches would be higher as compared to salads or ice cream which causes the stepwise pattern.
Answer:
qqnorm(mcd$total_carb, main = "Dairy Queen Carbs")
qqline(mcd$total_carb)The normal probability plot mimics a little bit of right skewness with long tail and we can confirm that with histogram as shown below:
hist(mcd$total_carb)