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.
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.
## # A tibble: 6 × 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
## # ℹ 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")
Centers: Compare the median values of calories from fat. Mcdonalds is 240 and Dairy Queen is 220. The median calories from fat for McDonald’s is higher than that for Dairy Queen.
Shapes: Mcdonalds: it has a long tail to the right (positively skewed), this indicates that there are some high-calorie items that are affecting the average. Dairy Queen: the density plot shows a more uniform distribution and have multiple peaks, this suggests variability in menu items.
Spreads: The spread in calories from fat (IQR) and the presence of outliers indicate that McDonald’s has more variability in high-calorie items compared to Dairy Queen.
# Filter data for McDonald's and Dairy Queen
fastfood_combined <- fastfood %>%
filter(restaurant %in% c("Mcdonalds", "Dairy Queen"))
# Create a boxplot
ggplot(fastfood_combined, aes(x = restaurant, y = cal_fat, fill = restaurant)) +
geom_boxplot() +
labs(title = "Calories from Fat in McDonald's and Dairy Queen Menu Items",
x = "Restaurant",
y = "Calories from Fat") +
theme_minimal()
# Create a density plot
ggplot(fastfood_combined, aes(x = cal_fat, fill = restaurant)) +
geom_density(alpha = 0.5) +
labs(title = "Density Plot of Calories from Fat",
x = "Calories from Fat",
y = "Density") +
theme_minimal()
# Calculate summary statistics
summary_stats <- fastfood_combined %>%
group_by(restaurant) %>%
summarise(
count = n(),
mean_calories_fat = mean(`cal_fat`, na.rm = TRUE),
median_calories_fat = median(`cal_fat`, na.rm = TRUE),
sd_calories_fat = sd(`cal_fat`, na.rm = TRUE),
min_calories_fat = min(`cal_fat`, na.rm = TRUE),
max_calories_fat = max(`cal_fat`, na.rm = TRUE)
)
print(summary_stats)
## # A tibble: 2 × 7
## restaurant count mean_calories_fat median_calories_fat sd_calories_fat
## <chr> <int> <dbl> <dbl> <dbl>
## 1 Dairy Queen 42 260. 220 156.
## 2 Mcdonalds 57 286. 240 221.
## # ℹ 2 more variables: min_calories_fat <dbl>, max_calories_fat <dbl>
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.
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.
the histogram and the normal curve align closely we can conclude that the data appear to follow a nearly normal distribution.
# Calculate mean and standard deviation for Dairy Queen calories from fat
dqmean <- mean(dairy_queen$cal_fat, na.rm = TRUE)
dqsd <- sd(dairy_queen$cal_fat, na.rm = TRUE)
# Create a density histogram with a normal curve overlay
ggplot(data = dairy_queen, aes(x = cal_fat)) +
geom_blank() +
geom_histogram(aes(y = ..density..), binwidth = 10, fill = "lightblue", color = "black") +
stat_function(fun = dnorm, args = c(mean = dqmean, sd = dqsd), col = "tomato") +
labs(title = "Density Histogram of Calories from Fat in Dairy Queen Products",
x = "Calories from Fat",
y = "Density") +
theme_minimal()
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”.
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
.
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.)# Create a normal probability plot for the simulated normal data
ggplot(data = NULL, aes(sample = sim_norm)) +
geom_line(stat = "qq") +
labs(title = "Q-Q Plot of Simulated Normal Data",
x = "Theoretical Quantiles",
y = "Sample Quantiles") +
theme_minimal()
Points Closely Following the Line: Since sim_norm is generated from a normal distribution, all or most of the points should fall very close to the diagonal line (the 45-degree line). This indicates that the simulated data is nearly normal.
For the Real Data: We observe points that closely follow the diagonal line but have some deviations, especially in the upper tail, this suggests that while the data is roughly normal, there are some outliers or skewness affecting it.
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.
Yes, the normal probability plot for the calories from fat in Dairy Queen products does look similar to the plots created for the simulated data. The real data shows some deviations, indicating it is roughly normal but not perfectly so, suggesting that while it approximates normality, it is influenced by some outliers or skewness.
there are significant deviations (especially in the upper tail), this indicates that the data may not be perfectly normal.
# Filter for McDonald's data
mcdonalds <- fastfood %>%
filter(restaurant == "Mcdonalds")
# Calculate mean and standard deviation
mcmean <- mean(mcdonalds$cal_fat)
mc_sd <- sd(mcdonalds$cal_fat)
# Q-Q plot for McDonald's data
qqnormsim(sample = mcdonalds$cal_fat, data = mcdonalds)
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] 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.
## # 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.
mc_mean <- mean(mcdonalds$cal_fat)
mc_sd <- sd(mcdonalds$cal_fat)
# Theoretical Probability
p_theoretical_mc <- 1 - pnorm(q = 400, mean = mc_mean, sd = mc_sd)
dq_mean <- mean(dairy_queen$cal_fat)
dq_sd <- sd(dairy_queen$cal_fat)
# Theoretical Probability
p_theoretical_dq <- pnorm(q = 200, mean = dq_mean, sd = dq_sd)
p_empirical_mc <- mcdonalds %>%
filter(cal_fat > 400) %>%
summarise(percent = n() / nrow(mcdonalds))
p_empirical_dq <- dairy_queen %>%
filter(cal_fat < 200) %>%
summarise(percent = n() / nrow(dairy_queen))
For McDonald’s Data:
Theoretical Probability P(X > 400) = 0.30 Empirical Probability P(X > 400) = 0.15
For Dairy Queen Data:
Theoretical Probability P(X < 200) = 0.34 Empirical Probability P(X < 200) = 0.42
Arby’s has the highest p-value of 0.199, which is above the common significance threshold of 0.05. This suggests that the sodium distribution for Arby’s is the closest to normal among the restaurants listed.
sodium_stats <- fastfood %>%
group_by(restaurant) %>%
summarise(mean_sodium = mean(sodium, na.rm = TRUE),
sd_sodium = sd(sodium, na.rm = TRUE),
n = n()) %>%
filter(n > 5) # Only include restaurants with more than 5 items
library(ggplot2)
# Create a function to generate Q-Q plots for sodium
create_qq_plot <- function(data, restaurant_name) {
ggplot(data, aes(sample = sodium)) +
geom_line(stat = "qq") +
ggtitle(paste("Q-Q Plot for", restaurant_name)) +
theme_minimal()
}
# Loop through each restaurant and create Q-Q plots
for (res in unique(fastfood$restaurant)) {
restaurant_data <- fastfood %>%
filter(restaurant == res)
print(create_qq_plot(restaurant_data, res))
}
normality_results <- fastfood %>%
group_by(restaurant) %>%
summarise(shapiro_test = list(shapiro.test(sodium)),
n = n()) %>%
filter(n > 5) # Only include restaurants with more than 5 items
# Extract the p-values from the results
normality_results <- normality_results %>%
mutate(p_value = map_dbl(shapiro_test, ~ .x$p.value)) %>%
select(restaurant, p_value)
# View the results
print(normality_results)
## # A tibble: 8 × 2
## restaurant p_value
## <chr> <dbl>
## 1 Arbys 0.199
## 2 Burger King 0.133
## 3 Chick Fil-A 0.00250
## 4 Dairy Queen 0.0000471
## 5 Mcdonalds 0.0000000446
## 6 Sonic 0.00000178
## 7 Subway 0.0000251
## 8 Taco Bell 0.000699
The stepwise pattern in the normal probability plots for sodium distributions likely occurs because of discrete values in the data there are several reasons such as: 1. Rounding and Grouping 2. Limited precison 3. Discrete Nature of Data.
# Choose a restaurant, e.g., McDonald's
restaurant_data <- fastfood %>%
filter(restaurant == "Mcdonalds")
# Normal probability plot (Q-Q plot) for total carbohydrates
ggplot(data = restaurant_data, aes(sample = total_carb)) +
geom_qq() +
geom_qq_line() +
ggtitle("Normal Q-Q Plot for Total Carbohydrates at McDonald's")
# Histogram for total carbohydrates
ggplot(data = restaurant_data, aes(x = total_carb)) +
geom_histogram(binwidth = 10, fill = "lightblue", color = "black") +
ggtitle("Histogram of Total Carbohydrates at McDonald's")