# You can run this code to install the pak package, and then
# use pak to install the stat1080r package from github.
install.packages("pak")
pak::pak("https://github.com/beanb2/stat1080r")Homework 2 - STAT 1080
Introduction
This assignment will give you experience visualizing and interpreting numerical information. You won’t need to bring in your own datasets — everything you need comes from R packages. Homework datasets and solutions are included in the stat1080r course package, so make sure you have the latest version installed before you begin.
You’ll complete this file by finishing the code and filling in the answer prompts. Replace each #...# with the code needed to answer the question. Sometimes I’ll give you a code “shell” (marked with ##) that you’ll need to uncomment and complete.
When you’re done, submit your .qmd file in Canvas. Be sure it successfully renders to HTML with all your answers showing. Don’t forget to check the style guidelines at the end before submitting. Note that you must use the “modern” pipe command |> in your code. Please avoid the use of the old %>% in your code which will result in a loss of points.
There are 3 problems in this assignment (each with several parts), worth a total of 80 points.
Problem 1 - Cereal Data Histograms (27 points)
We will be using the same cereals dataset that we used in Homework 1.
library(tidyverse)
library(stat1080r)
head(cereal) Shelf Name Manufacturer Type Calories Protein Fat
1 Top 100%_Bran N C 70 4 1
2 Top 100%_Natural_Bran Q C 120 3 5
3 Top All-Bran K C 70 4 1
4 Top All-Bran_with_Extra_Fiber K C 50 4 0
5 Top Almond_Delight R C 110 2 2
6 Bottom Apple_Cinnamon_Cheerios G C 110 2 2
Sodium Fiber Carbohydrates Sugars Potassium Vitamins Weight Cups
1 130 10.0 5.0 6 280 25 1 0.33
2 15 2.0 8.0 8 135 0 1 1.00
3 260 9.0 7.0 5 320 25 1 0.33
4 140 14.0 8.0 0 330 25 1 0.50
5 200 1.0 14.0 8 NA 25 1 0.75
6 180 1.5 10.5 10 70 25 1 0.75
glimpse(cereal)Rows: 77
Columns: 15
$ Shelf <chr> "Top", "Top", "Top", "Top", "Top", "Bottom", "Middle", "…
$ Name <chr> "100%_Bran", "100%_Natural_Bran", "All-Bran", "All-Bran_…
$ Manufacturer <chr> "N", "Q", "K", "K", "R", "G", "K", "G", "R", "P", "Q", "…
$ Type <chr> "C", "C", "C", "C", "C", "C", "C", "C", "C", "C", "C", "…
$ Calories <int> 70, 120, 70, 50, 110, 110, 110, 130, 90, 90, 120, 110, 1…
$ Protein <int> 4, 3, 4, 4, 2, 2, 2, 3, 2, 3, 1, 6, 1, 3, 1, 2, 2, 1, 1,…
$ Fat <int> 1, 5, 1, 0, 2, 2, 0, 2, 1, 0, 2, 2, 3, 2, 1, 0, 0, 0, 1,…
$ Sodium <int> 130, 15, 260, 140, 200, 180, 125, 210, 200, 210, 220, 29…
$ Fiber <dbl> 10.0, 2.0, 9.0, 14.0, 1.0, 1.5, 1.0, 2.0, 4.0, 5.0, 0.0,…
$ Carbohydrates <dbl> 5.0, 8.0, 7.0, 8.0, 14.0, 10.5, 11.0, 18.0, 15.0, 13.0, …
$ Sugars <int> 6, 8, 5, 0, 8, 10, 14, 8, 6, 5, 12, 1, 9, 7, 13, 3, 2, 1…
$ Potassium <int> 280, 135, 320, 330, NA, 70, 30, 100, 125, 190, 35, 105, …
$ Vitamins <int> 25, 0, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 2…
$ Weight <dbl> 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.33, 1.00, 1.…
$ Cups <dbl> 0.33, 1.00, 0.33, 0.50, 0.75, 0.75, 1.00, 0.75, 0.67, 0.…
Part a (2 points)
First, remove the rows that contain missing (i.e., NA) values for Sugars using the filter() function with a tidyverse pipe (i.e., |>).
## cereal_sug <- #...#
# REMEMBER TO UNCOMMENT ALL ## LINES before submitting!
# This line will test whether you have gotten the correct result
## all.equal(cereal_sug, hw2_sol[["cereal_sug"]])Part b (5 points)
Create an unrefined histogram of the sugar content of cereals. Note the R code chunk options I am using to help with the formatting of the HTML documents. Visually check your answer against the solution. They should be visually identical.
# Note the "header" options above that determine how the figure is formatted.
## ggplot(cereal_sug, aes(#...#)) +
## geom_#...#()Part c (5 points)
Visuals often need refinement before we present them to other people. One way to accomplish this is through ggplot themes. We will use the following theme throughout the remainder of this assignment, which does the following.
- Changes the plot background from grey to white and changes the plot grid lines from white to gray.
- Increases the size of the fonts for all plots and legend labels.
- Centers plot titles whenever they are present.
- Moves any plot legends (when applicable) to the bottom of each plot.
# Do not change this code, but be sure to run this code
# before you try to do anything else!
my_theme <- theme_bw() +
theme(
text = element_text(size = 14),
plot.title = element_text(hjust = 0.5),
legend.position = "bottom"
)Using this theme, create a refined version of the histogram you created in Part b. Your refined histogram should visually match the solution provided on canvas. Some of the refinements you need to make (or that the partial code already does for you) are as follows:
- Remove the y-axis label and change the x-axis label using
xlab()andylab(). - Adjust the limits and the breaks of the axis labels using
scale_x_continuous()andscale_y_continuous(), using the visual solution to guide your inputs. - Use the
breaksargument ingeom_histogram()to make the bins of length 1 starting at 0 and ending at 16. - Use the
colorandfillarguments ingeom_histogramto make “black” boundaries and “gray50” fill for the rectangles. - Use the custom theme we created above.
## ggplot(cereal_sug, #...#) +
## geom_histogram(breaks = #...#,
## col = "black", fill = "gray50") +
## scale_x_continuous(breaks = #...#) +
## scale_y_continuous(limits = #...#,
## breaks = #...#) +
## xlab(#...#) +
## ylab("") +
## my_themePart d (5 points)
Please describe in 1-3 sentences what the histogram suggests about the shape of the distribution of the sugar content in cereals. Comment specifically: does sugar content appear to follow a normal distribution? Explain why or why not.
Replace this text with your answer
Part e (5 points)
Create a series of three histograms, one for each shelf, of the sugar content in cereals using the facet_wrap() function. Make it so the histograms are vertically aligned, which will facilitate comparisons in the distribution shape. Adjust the y-axis to eliminate unnecessary white space in the plot. Be sure that your final plot visually matches the solution plot provided.
## ggplot(cereal_sug, aes(#...#)) +
## #...# # adapt code from previous problem here
## facet_wrap(#...#, ncol = 1) +
## xlab(#...#) +
## ylab(#...#) +
## my_themePart f (5 points)
DISCUSS: Please write 2-4 sentences to compare the shape of the distribution of cereal sugar amounts per serving based on shelf. Comment specifically: Do any of the distributions seem to follow a normal distribution?
Replace this text with your answer
Problem 2 - Cereal Data Density Plots and Boxplots (23 points)
Part a (5 points)
Create a single plot with three colored density curves of cereal sugar content, with each color representing a different cereal shelf. For this plot, make the same kind refinements, as necessary, that you did for the histogram, (obviously excluding the refinement that was specific to the histogram bin widths). Note that the code to color the density lines is provided to you. Additional color palettes are available at https://colorbrewer2.org/, in the tayloRswift package (for palettes drawn from albums), and in the ggsci package (for palettes from TV shows and media outlets).
## ggplot(#...#) +
## geom_#...#(lwd = 1) +
## scale_color_brewer(type = "qual", palette = "Dark2") +
## xlab(#...#) +
## my_themePart b (5 points)
Name at least one advantage of the density plot representation of the distribution as compared to the three histogram representation. Name at least one disadvantage.
Replace this text with your answer
Part c (3 points)
In Part (d) we will create side-by-side boxplots of the sugar content of the cereals on the three different shelves. In order to follow the best-practices of good statistical graphics, we wish to order the boxplots on the x-axis so that the shelf with the smallest median sugar content appears on the far left, while the shelf with the largest median sugar content appears on the far right. To accomplish this, we need to re-factor the Shelf variable in the order that we want. Please write a tidyverse chain that completes this arrangement and saves it as a vector that matches the provided solution.
## shelf_order <- cereal_sug |>
## group_by(#...#) |>
## summarize(sugars_median = #...#) |>
## arrange(#...#) |>
## pull(Shelf) # grab the vector of shelves.
## all.equal(shelf_order, hw2_sol[["shelf_order"]])Part d (5 points)
Create side-by-side boxplots as described in Part (c), please use strategies from the previous problem parts to make your answer visually match the one provided in the solution.
# Uncomment this line for your boxplot. No need to change anything
## cereal_sug2 <- cereal_sug |>
## mutate(Shelf = factor(Shelf, levels = shelf_order))
## ggplot(cereal_sug2) +
## #...#Part e (5 points)
Identify at least one way in which this visual is better than the histogram or density plots we have made previously. Identify at least one way in which this visual is worse.
Replace this text with your answer
Problem 3 Utah Snow Loads (20 points)
The rt_load_ut dataset in the stat1080r package contains the design snow loads for the state of Utah. A design snow load is the weight in snow that a roof must be able to withstand in order to ensure that the building will keep its occupants safe during the winter. The values you are working with are the actual design standard values developed by Dr. Brennan Bean in 2020. Please check out ?rt_load_ut for additional documentation for the data set.
Part a (5 points)
Create a scatterplot with site elevation on the x-axis and design snow load (load) on the y-axis, color the points based on their ecological region (eco_region). Note that the code below uses a log2 transformation for the y-axis and re-labels the x-axis to be in thousands of feet.
## ggplot(rt_load_ut, #...#) +
## geom_#...#() +
## scale_y_continuous(trans = "log2", breaks = 2^(1:10),
## limits = c(16, 1024)) +
## scale_x_continuous(breaks = seq(3000, 11000, 2000),
## labels = seq(3, 11, 2)) +
## scale_color_brewer(#...#) +
## xlab(#...#) +
## ylab(#...#) +
## my_themePart b (5 points)
What can you say about the relationship between ground snow loads and elevation? How do the points from the two eco-regions differ? In what ways are the points from the two regions similar? What data properties would be better visualized using histograms or boxplots as compared to this scatterplot? Please answer these questions in a single paragraph.
Replace this text with your answer
Part c (5 points)
Repeat the plot in Part a, but plot latitude on the x-axis instead of elevation. Change the scale_x_continuous arguments to reflect the change in scale associated with this new variable.
## ggplot(rt_load_ut) +
## #...#
## scale_y_continuous(trans = "log2", breaks = 2^(1:10),
## limits = c(16, 1024)) +
## scale_x_continuous(limits = c(37, 42)) +
## scale_color_brewer(#...#) +
## #...# +
## my_themePart d (5 points)
How does the relationship between latitude and snow load compare to the relationship between elevation and snow load? Comment briefly.
Replace this text with your answer.
Submission Style (10 points)
Each submission should have the following elements:
You should submit the
.qmdfile (not theHTMLrendering) with a file name in the style of<last_name>_<first_name>_homework2.qmd.Your
.qmdfile should run without errors when the grader attempts to render it to a html.Your code needs to run “clean” on any lintr checks. Please see the brief videos available on the “Style Guides” tabs of the course canvas page that introduce you to
lintr, andstyler. Note that you can ignore any flags with the tags:trailing_whitespace_linter,trailing_blank_lines_linter, andcommented_code_linter.