From 410c1124696b39b2a64f6f0e4d998cc5c27660b7 Mon Sep 17 00:00:00 2001 From: GitHub Actions Date: Fri, 24 Dec 2021 21:11:58 +0000 Subject: [PATCH] Re-build Rmd --- 01_intro_to_r/intro_to_r.html | 6 +- 02_intro_to_data/intro_to_data.html | 2 +- .../normal_distribution.html | 1409 ++++++++++++++++- 3 files changed, 1372 insertions(+), 45 deletions(-) diff --git a/01_intro_to_r/intro_to_r.html b/01_intro_to_r/intro_to_r.html index ef1e5f6..893691e 100644 --- a/01_intro_to_r/intro_to_r.html +++ b/01_intro_to_r/intro_to_r.html @@ -1732,7 +1732,7 @@

Data visualization

R has some powerful functions for making graphics. We can create a simple plot of the number of girls baptized per year with the following code:

ggplot(data = arbuthnot, aes(x = year, y = girls)) + 
   geom_point()
-

+

In this code, we use the ggplot() function to build a plot. If you run this code chunk, a plot will appear below the code chunk. The R Markdown document displays the plot below the code that was used to generate it, to give you an idea of what the plot would look like in a final report.

The command above also looks like a mathematical function. This time, however, the function requires multiple inputs (arguments), which are separated by commas.

With ggplot():

@@ -1748,7 +1748,7 @@

Data visualization

Since we want to scatterplot, we use geom_point(). This tells ggplot() that each data point should be represented by one point on the plot. If you wanted to visualize the above plot using a line graph instead of a scatterplot, you would replace geom_point() with geom_line(). This tells ggplot() to draw a line from each observation with the next observation (sequentially).

ggplot(data = arbuthnot, aes(x = year, y = girls)) +
   geom_line()
-

+

Use the plot to address the following question:

  1. Is there an apparent trend in the number of girls baptized over the years? How would you describe it? (To ensure that your lab report is comprehensive, be sure to include the code needed to make the plot as well as your written interpretation.)
  2. @@ -1784,7 +1784,7 @@

    Adding a new variable to the data frame

    You can make a line plot of the total number of baptisms per year with the following code:

    ggplot(data = arbuthnot, aes(x = year, y = total)) + 
       geom_line()
    -

    +

    In an similar fashion, once you know the total number of baptisms for boys and girls in 1629, you can compute the ratio of the number of boys to the number of girls baptized with the following code:

    5218 / 4683

    Alternatively, you could calculate this ratio for every year by acting on the complete boys and girls columns, and then save those calculations into a new variable named boy_to_girl_ratio:

    diff --git a/02_intro_to_data/intro_to_data.html b/02_intro_to_data/intro_to_data.html index 52def96..21855ed 100644 --- a/02_intro_to_data/intro_to_data.html +++ b/02_intro_to_data/intro_to_data.html @@ -1854,7 +1854,7 @@

    More Practice

  3. Make a scatterplot of avg_speed vs. distance. Describe the relationship between average speed and distance. Hint: Use geom_point().

  4. Replicate the following plot. Hint: The data frame plotted only contains flights from American Airlines, Delta Airlines, and United Airlines, and the points are colored by carrier. Once you replicate the plot, determine (roughly) what the cutoff point is for departure delays where you can still expect to get to your destination on time.

-

+


Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.

diff --git a/04_normal_distribution/normal_distribution.html b/04_normal_distribution/normal_distribution.html index 3c37c62..dd34d45 100644 --- a/04_normal_distribution/normal_distribution.html +++ b/04_normal_distribution/normal_distribution.html @@ -13,13 +13,36 @@ The normal distribution - - + - - - - + + + + - - - - + + + + + @@ -335,8 +1662,8 @@

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(tidyverse)
+library(openintro)

Creating a reproducible lab report

@@ -346,9 +1673,9 @@

Creating a reproducible lab report

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.

-
library(tidyverse)
-library(openintro)
-head(fastfood)
+
library(tidyverse)
+library(openintro)
+head(fastfood)
## # A tibble: 6 × 17
 ##   restaurant item       calories cal_fat total_fat sat_fat trans_fat cholesterol
 ##   <chr>      <chr>         <dbl>   <dbl>     <dbl>   <dbl>     <dbl>       <dbl>
@@ -364,10 +1691,10 @@ 

The data

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")
+
mcdonalds <- fastfood %>%
+  filter(restaurant == "Mcdonalds")
+dairy_queen <- fastfood %>%
+  filter(restaurant == "Dairy Queen")
  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?
@@ -377,13 +1704,13 @@

The data

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.

-
dqmean <- mean(dairy_queen$cal_fat)
-dqsd <- sd(dairy_queen$cal_fat)
+
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")
+
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 calories from fat. 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.

  1. Based on the this plot, does it appear that the data follow a nearly normal distribution?
  2. @@ -392,19 +1719,19 @@

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

    -
    ggplot(data = dairy_queen, aes(sample = cal_fat)) +
    -  geom_line(stat = "qq")
    +
    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)
    +
    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.

    1. 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? (Since sim_norm is not a dataframe, it can be put directly into the sample argument and the data argument can be dropped.)

    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)
    +
    qqnormsim(sample = cal_fat, data = dairy_queen)
    1. 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?

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

    3. @@ -415,12 +1742,12 @@

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

      -
      dairy_queen %>%
      -  filter(cal_fat > 600) %>%
      -  summarise(percent = n() / nrow(dairy_queen))
      +
      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.

      1. 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?