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 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
## # i 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")
dairy_queen$cal_fat
## [1] 660 460 330 270 310 160 310 480 590 240 220 220 180 160 180 80 80 410 670
## [20] 440 140 200 160 310 240 130 430 310 430 180 180 220 280 120 270 190 170 20
## [39] 140 130 0 240
#DairyQueen Histogram
ggplot(data = dairy_queen, aes(x=cal_fat)) + geom_histogram()
mcdonalds$cal_fat
## [1] 60 410 600 280 410 250 100 210 190 400 170 300 180 300 70
## [16] 50 330 190 310 130 160 200 300 160 280 200 200 240 320 180
## [31] 300 340 200 320 190 250 390 630 790 1270 100 140 240 480 960
## [46] 240 360 600 70 80 250 110 120 250 90 100 230
ggplot(data = mcdonalds, aes(x= cal_fat)) + geom_histogram ()
ANS: Dairy Queen’s distribution is more normal than McDonalds, which is
right/positive skewed.
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.
ANS: The data distribution appears nearly normal though not symmetrical. There may be outliers that are skewing the data.
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.)#Normal probability plot of sim_norm
ggplot(data = NULL, aes(sample = sim_norm)) +
geom_line(stat = 'qq')
ANS: The simulations are similar and seem within a reasonable margin of error, but they seem to account for lower values between the -2 to -1 quantile than the real data does which shows more of a left skew.
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)
ANS: Yes there are some that look similiar, particularly sim6,sim7 and sim8, indicating that our distribution is fairly normal.
mdmean <- mean(mcdonalds$cal_fat)
mdsd <- sd(mcdonalds$cal_fat)
set.seed(59)
sim_norm <- rnorm(n = nrow(mcdonalds), mean = mdmean, sd = mdsd)
qqnormsim(sample = cal_fat, data = mcdonalds)
ANS The McDonald’s distribution appears normal though not at the same
“slope” as that of Dairy Queen. The simulations are similar to the data
but with a higher slope [not sure if this is the right terminology].
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.
My question: What is the probability that Arbys has items on their menu with total carbs per item is greater than of 30 and sodium less than 1500?
#filter for Arby's restaurant
Arbys <- fastfood %>%
filter(restaurant == "Arbys")
Arbys
## # A tibble: 55 x 17
## restaurant item calories cal_fat total_fat sat_fat trans_fat cholesterol
## <chr> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 Arbys Arby's M~ 330 100 11 4 0 30
## 2 Arbys Arby-Q S~ 400 90 10 3 0 30
## 3 Arbys Beef 'n ~ 450 180 20 6 1 50
## 4 Arbys Beef 'n ~ 630 290 32 11 1.5 100
## 5 Arbys Bourbon ~ 650 300 33 12 1 105
## 6 Arbys Bourbon ~ 690 280 31 9 0 90
## 7 Arbys Bourbon ~ 690 280 31 9 0 90
## 8 Arbys Buttermi~ 540 220 24 4.5 0 60
## 9 Arbys Buttermi~ 650 280 31 9 0 90
## 10 Arbys Buttermi~ 690 310 35 10 0 110
## # i 45 more rows
## # i 9 more variables: sodium <dbl>, total_carb <dbl>, fiber <dbl>, sugar <dbl>,
## # protein <dbl>, vit_a <dbl>, vit_c <dbl>, calcium <dbl>, salad <chr>
#find mean and sd for carbs and sodium
abcarbsmean <- mean(Arbys$total_carb)
abcarbssd <- sd(Arbys$total_carb)
abNAmean <- mean(Arbys$sodium)
abNAsd <- sd(Arbys$sodium)
total_carbs <- pnorm(q= 50, mean = abcarbsmean, sd = abcarbssd)
total_carbs
## [1] 0.6058411
abNA <- pnorm( q = 50, mean = abNAmean, sd = abNAsd)
#filter for carbs greater than 30
total_carbs50 <- Arbys %>%
filter(total_carb > 50) %>%
summarise(percent = n()/nrow(Arbys))
total_carbs50
## # A tibble: 1 x 1
## percent
## <dbl>
## 1 0.364
print("The percentage of items with more than 50 carbs is 36%")
## [1] "The percentage of items with more than 50 carbs is 36%"
#filter for sodium less than 1500
total_NA1500 <- Arbys %>%
filter(sodium < 1500) %>%
summarise(percent = n()/nrow(Arbys))
total_NA1500
## # A tibble: 1 x 1
## percent
## <dbl>
## 1 0.509
print("The percentage of items with 1500 or less of sodium is 51%")
## [1] "The percentage of items with 1500 or less of sodium is 51%"
#Density histogram of > 50 total_carbs at Arbys
ggplot(data = Arbys, aes (x = total_carb)) +
geom_blank () +
geom_histogram(aes(y = ..density..)) +
stat_function(fun = dnorm, args = c(mean = abcarbsmean, sd = abcarbssd), col = "tomato")
#Density histogram of < 1500 sodium at Arbys
ggplot(data = Arbys, aes (x = sodium)) +
geom_blank () +
geom_histogram(aes(y = ..density..)) +
stat_function(fun = dnorm, args = c(mean = abNAmean, sd = abNAsd), col = "tomato")
#Histograms Sodium in all Restaurants
fastfood %>%
group_by(restaurant) %>%
ggplot() +
geom_histogram(aes(x = sodium), bins = 15) +
ggtitle("Sodium in Fast Food Restaurants") +
xlab("Sodium") +
ylab("Count") +
facet_wrap(. ~restaurant)
ANS There are a number of foods served at each restaurant that have lower sodium values
#filter for Subway's restaurant
Subway <- fastfood %>%
filter(restaurant == "Subway")
Subway
## # A tibble: 96 x 17
## restaurant item calories cal_fat total_fat sat_fat trans_fat cholesterol
## <chr> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 Subway "6\" B.L~ 320 80 9 4 0 20
## 2 Subway "Footlon~ 640 160 18 8 0 40
## 3 Subway "6\" BBQ~ 430 160 18 6 0 50
## 4 Subway "Footlon~ 860 320 36 12 0 100
## 5 Subway "6\" Big~ 580 310 31 11 0 85
## 6 Subway "Footlon~ 1160 620 62 22 0 170
## 7 Subway "6\" Big~ 500 150 17 9 1 85
## 8 Subway "Footlon~ 1000 300 34 18 2 170
## 9 Subway "Kids Mi~ 180 20 3 0.5 0 10
## 10 Subway "6\" Bla~ 290 40 5 1 0 20
## # i 86 more rows
## # i 9 more variables: sodium <dbl>, total_carb <dbl>, fiber <dbl>, sugar <dbl>,
## # protein <dbl>, vit_a <dbl>, vit_c <dbl>, calcium <dbl>, salad <chr>
#Probability Plot
Subway_pp <- ggplot(data = Subway, aes(sample = total_carb)) +
geom_line(stat = "qq")
Subway_pp
#Subway's histogram
Subway <- ggplot(Subway, aes(x=total_carb)) +
geom_histogram() +
xlab("Total Carbohydrates") +
ylab("Frequency") +
ggtitle("Subway's Total Carbohydrates")
Subway
Subway <- fastfood %>%
filter(restaurant == "Subway")
Subway
## # A tibble: 96 x 17
## restaurant item calories cal_fat total_fat sat_fat trans_fat cholesterol
## <chr> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 Subway "6\" B.L~ 320 80 9 4 0 20
## 2 Subway "Footlon~ 640 160 18 8 0 40
## 3 Subway "6\" BBQ~ 430 160 18 6 0 50
## 4 Subway "Footlon~ 860 320 36 12 0 100
## 5 Subway "6\" Big~ 580 310 31 11 0 85
## 6 Subway "Footlon~ 1160 620 62 22 0 170
## 7 Subway "6\" Big~ 500 150 17 9 1 85
## 8 Subway "Footlon~ 1000 300 34 18 2 170
## 9 Subway "Kids Mi~ 180 20 3 0.5 0 10
## 10 Subway "6\" Bla~ 290 40 5 1 0 20
## # i 86 more rows
## # i 9 more variables: sodium <dbl>, total_carb <dbl>, fiber <dbl>, sugar <dbl>,
## # protein <dbl>, vit_a <dbl>, vit_c <dbl>, calcium <dbl>, salad <chr>
#Mean and standard deviation for Subway
s_mean <- mean(Subway$total_carb)
s_sd <- sd(Subway$total_carb)
#Density Histogram
ggplot(data = Subway, aes(x = total_carb)) +
geom_blank() +
geom_histogram(aes(y = ..density..)) +
stat_function(fun = dnorm, args = c(mean = s_mean, sd = s_sd), col = "tomato")