---
title: "Lab 10: The Normal Distribution"
author: "Insert Name"
output:
  pdf_document
 
---

```{r, include = FALSE, message = FALSE}
library(tidyverse)
library(openintro)
```

# Due: 12am night before lab

# Instructions
Work through the problems below, and submit this document as a knitted .pdf file with answers to the Problem Set 1 assignment on Gradescope. 


**For each problem, put your solution between the bars of red stars.**


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


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

```{r}
data(fastfood)
glimpse(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.

```{r}
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?

***********************************************

***********************************************

## The normal distribution

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.

```{r}
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.

```{r}
ggplot(data = dairy_queen, aes(x = cal_fat)) +
  geom_histogram(aes(y = ..density..), color = "white", bins = 15) +
  stat_function(fun = dnorm, args = c(mean = dqmean, sd = dqsd), color = "tomato")
```

The first layer of the plot above 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.

### Exercise 2

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

***********************************************

***********************************************

## 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".

```{r}
ggplot(data = dairy_queen, aes(sample = cal_fat)) +
  geom_point(stat = "qq")
```

This time, you can use the `geom_point()` 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`.

```{r}
sim_norm <- rnorm(n = nrow(dairy_queen), mean = dqmean, sd = dqsd)
sim_norm_df <- data.frame(sim_norm)
```

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?

***********************************************

***********************************************


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.


```{r}
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?

***********************************************

***********************************************

### Exercise 5

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

***********************************************

***********************************************

## Normal probabilities

Now we have a slew of tools to judge whether or not a variable is normally distributed.
Why should we 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. For example, consider the question "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 probability in the Normal distribution. In R, this is done in one step with the function `pnorm()`.

```{r}
1 - pnorm(q = 600, mean = dqmean, sd = dqsd)
```

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.

```{r}
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.



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

***********************************************

***********************************************


### Exercise 7

Now let's consider some of the other variables in the dataset. Use `facet_wrap` to create a probability plot for each restaurant in the dataset. Which one has a distribution that is the closest to Normal for sodium? (Hint: include scale = "free" inside your `facet_wrap` layer so that each plot has its own vertical axis scale.)

***********************************************

***********************************************



### Exercise 8

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

***********************************************

***********************************************

## Computing Inverse Probabilities

The Graduate Record Exam (GRE) is a standardized test which serves as an admission requirement for many graduate schools, and has an analytic writing section and two multiple choice sections: Verbal Reasoning and Quantitative Reasoning. Due to forced Normalization in scores, both sections are approximately Normal. The mean score for Verbal Reasoning section was 462 with a standard deviation of 119, and the mean score for the Quantitative Reasoning was 584 with a standard deviation of 151.

We will use the above information to explore the use of the R functions `pnorm` and `qnorm`.

 * `pnorm` will return the **percentile**, or cumulative area of the curve to the left of a point on the x-axis, $q$, called a **quantile**.  
 
 * `qnorm` will return the value on the x-axis for a given **percentile**.
 
 
## Using `pnorm`
 
For instance, say a student earns a score of 650 on the Verbal Reasoning section of the exam.  Then to find the percentile for this student.

```{r}

tibble(
  percentile = pnorm(650,mean=462,sd=119)
)

```

Thus we see that the student is in the 94th percentile.  That is 94% of the values in the distribution are to the left of 650.  This is shown as the shaded region in the visualization below.

```{r, echo=FALSE}

min_val<-0
max_val<-1000

score = 650
m = 462
std = 119

ggplot(data.frame(x = c(min_val, max_val)), aes(x = x)) + 
    stat_function(fun = dnorm, args = list(mean = m, sd = std)) + 
    stat_function(fun = dnorm, args = list(mean = m, sd = std), xlim = c(min_val, score),
                  geom = "area", fill = "#84CA72", alpha = .9) +
    scale_x_continuous(name = "Score", breaks = seq(min_val, max_val, std)) +
    scale_y_continuous(name="",breaks=NULL)

```

If we wanted to know what percentage of students scored better than 650, we calculate 1 minus the percentage to the left of the value.

```{r}

tibble(
  percent_better = 1 - pnorm(650,mean=462,sd=119)
)

```

The visualization below shows that this is, appropriately, in the right tail of the distribution.

```{r, echo=FALSE}

min_val<-0
max_val<-1000

score = 650
m = 462
std = 119

ggplot(data.frame(x = c(min_val, max_val)), aes(x = x)) + 
    stat_function(fun = dnorm, args = list(mean = m, sd = std)) + 
    stat_function(fun = dnorm, args = list(mean = m, sd = std), xlim = c(score, max_val),
                  geom = "area", fill = "#84CA72", alpha = .9) +
    scale_x_continuous(name = "Score", breaks = seq(min_val, max_val, std)) +
    scale_y_continuous(name="",breaks=NULL)

```

## Using `qnorm`

Now lets imagine that a student is told that they scored in the 57% percentile on the Quantitative Reasoning section of the exam.  To find their score for this student.

```{r}

tibble(
  score = qnorm(.57,mean=584, sd = 151)
)

```

This student's score is thus a 610.

```{r, echo=FALSE}

min_val<-0
max_val<-1000

score = 610
m = 584
std = 151

ggplot(data.frame(x = c(min_val, max_val)), aes(x = x)) + 
    stat_function(fun = dnorm, args = list(mean = m, sd = std)) + 
    stat_function(fun = dnorm, args = list(mean = m, sd = std), xlim = c(min_val, score),
                  geom = "area", fill = "#84CA72", alpha = .9) +
    scale_x_continuous(name = "Score", breaks = seq(min_val, max_val, std))+
    scale_y_continuous(name="",breaks=NULL)

```

### Exercise 9

What is the percentage of the students who score between 590 and 630 on the Quantitative Reasoning section?

*********************************************************************************

*********************************************************************************


### Exercise 10

What is the probability that a randomly selected student earns obtains a score greater than 600 on both multiple choice sections (assume, somewhat unrealistically, that scores on the two sections are independent)?

*********************************************************************************

*********************************************************************************

### Exercise 11

What score is needed on the Verbal Reasoning section to place in the top 10\%? What score is needed on the Quantitative Reasing section?

*********************************************************************************

*********************************************************************************


#### Standard Normal

Often it is useful to use the *Standard Normal*.  This is a normal distribution with a mean of 0 and a standard deviation of 1.  If we know that a value, $x$, is drawn from a normal distribution with a mean of $\mu$ and a standard deviation of $\sigma$, we can standardize it using the following formula:
$$
z = \frac{x - \mu}{\sigma}
$$
These standardized values are called **z-scores**.  We can calculate the z-score for the student who scored a 650 on the Verbal Reasoning section of the exam.

```{r}

score = 650
mu = 462
sigma = 119

tibble(
  z_score = (score - mu) / sigma
)

```

Note that for scores that are less than the mean, the z-score will be negative.  Imagine a student scored a 550 on the Quantitiative Reasoning section.

```{r}

score = 550
mu = 584
sigma = 151

tibble(
  z_score = (score - mu) / sigma
)

```

They have a z-score of -0.23.

### Exercise 12

A college senior scores 620 on the Verbal Reasoning section and 670 on the Quantitative Reasoning section. Calculate the student's z-scores for each section. 

*********************************************************************************

*********************************************************************************

### Exercise 13

In general, what does a z-score represent? On which section did the student in the previous part do better on (relative to the student's peers)? Find the student's percentile scores for the two sections.

*********************************************************************************

*********************************************************************************

