STAT 1080 - Fall 2026
  • Course Info
    • Overview
    • Syllabus
    • Support
    • Schedule
    • Useful links
  • Weekly Materials
    • W1. Introduction
    • W2. RStudio
    • W3. Correlation
    • W4. Programming
    • W5. Tidyverse
    • W6. Dates/Times and Distributions
    • W7. Data Visualization
    • W8. Statistics & Probability
    • W9. Data & Probability
    • W10. Random Variables
    • W11. Parameters & Estimates
    • W12. Statistical Inference
    • W13. Regression
    • W14. Regression
    • W15. Project Meetings

On this page

  • Introduction
  • Problem 1 - Cereal Data (40 points)
    • Part a (5 points)
    • Part b (5 points)
    • Part c (5 points)
    • Part d (5 points)
    • Part e (5 points)
    • Part f (10 points)
    • Part g (5 points)
  • Problem 2 - Cereal Data: Grouped Operations (30 points)
    • Part a (5 points)
    • Part b (5 points)
    • Part c (5 points)
    • Part d (5 points)
    • Part e (10 points)
  • Submission Style (10 points)
  • Submission Checklist
  • Report an issue

Homework 1 - STAT 1080

Author

(Put Name Here)

Introduction

This assignment will give you hands-on practice working with numerical summaries of data in R, using the tidyverse. 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 can install the package using the command install.packages("stat1080r", repos = "https://beanb2.r-universe.dev"). You should only have to install this package once during the semester.

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 longer sequence of code (a code “shell”, marked with ##) that you’ll need to uncomment and complete.

When you’re done, go through the checklist at the end of this file, and then submit your .qmd file in Canvas.

There are 2 problems in this assignment (each with several parts), worth a total of 80 points. 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.

Problem 1 - Cereal Data (40 points)

This problem will make use of the cereals dataset. The code below shows you how to look at the first six rows of that dataset.

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

The next line of code shows you how to explore the different variable types. Note that chr stands for a “character” variable, while int stands for “integer” (i.e., numbers with no decimals allowed) and dbl stands for “double” (i.e., numbers with decimals allowed).

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 (5 points)

Using tidyverse syntax, determine the mean, or average, added sugar content in a single serving of cereal, using all cereals with non-missing sugars information. Your solution should make use of the mean function in R. Check out the mean() function using ?mean to determine what options you have to remove missing values in your calculation.

Assign this value to the variable named sugar_mean_1. You will know that you have succeeded if the code chunk below prints the message TRUE when you render the document.

## sugar_mean_1 <- cereal |>
##   summarize(tmean = #...#) |>
##   pull(tmean)

## all.equal(sugar_mean_1, hw1_sol$sugar_mean_1)

Part b (5 points)

Now, write an equivalent expression that calculates the mean, without using the mean() function. For this, we will rely on the general definition of a mean. Let \(X\) represent a vector of values, with the individual elements of the vector denoted as \(x_1, x_2, \ldots, x_n\) respectively. Under this definition we can calculate the sample mean of \(X\) (called \(\bar{x}\)) as

\[\bar{x} = \frac{\sum_{i=1}^n x_i}{n}.\]

NoteMath Notation for the mean

Let’s break the math down a bit.

  • \(\bar{x}\) is the sample mean of the vector \(X\), which has values – \(x_1, x_2, ..., x_n\). We use capital letters for vectors and lower-case values for observations.
  • \(\sum_{i=1}^n\) says we’re going to take the sum of \(n\) things, which are indexed (\(i\) is the index of \(x_i\)) from 1 to \(n\).
  • We then divide the sum of the \(x_i\) (that is, the sum over \(X\)) by the length of \(X\), which is \(n\).

Restated in plain English, I am taking the sum of all the elements of the vector, and then dividing by the length of the vector (or, if I am ignoring NAs, the sum of instances for which !is.na() evaluates to TRUE).

NoteMissing Observations

Sometimes, we can have missing observations, which are denoted by NA. If there are missing observations, we should exclude the missing observations from the sum (in the numerator/on the top of the fraction), and then exclude the missing observations from the number of total observations.

In R, we can exclude NAs from most functions by using fn(..., na.rm = T), where fn is the function name and ... are the other arguments.

Using this definition, re-calculate the mean added sugar content of the cereals without using the mean() function in R. You may consider using functions in R that match one, or both, of the bolded words in the equation description. Remember that, should you have to remove any missing values as part of your calculation, you need to account for that in your estimation of the vector length. Assign this to the variable name sugar_mean_2 and use the last line of code to make sure that this calculation of the mean exactly matches the previous calculation.

## sugar_mean_2 <- cereal |>
##   summarize(tmean = #...#) |>
##   pull(tmean)

## all.equal(sugar_mean_2, hw1_sol$sugar_mean_1)

Part c (5 points)

Note that a “serving” of cereal is a relative measure: there is no standard weight OR volume to describe a serving of cereal. One way to know this is to take a look at the unique values of weight and cups in the cereal dataset. You can see these values by using the unique() function. A solution for weight_u is provided. Your task is to adapt the weight_u code to work for the cups_u calculation. Please ensure that the provided code prints a TRUE statement when the document is rendered.

weight_u <- cereal |> 
  pull(Weight) |>
  unique()

## cups_u <- #...#

## all.equal(cups_u, hw1_sol$cups_u)

Part d (5 points)

Based on what we learned in Part c, create a new variable in our data frame that represents “normalized” or “standardized” estimates of the added sugars in a “serving” of cereal. This variable should be named sugars_weight and should represent the total number of sugars per unit of Weight. Note that Weight is a standardized measure that represents the relative weight of a typical serving of cereal. It does not represent ounces, or grams, or other typical measurements of weight. Normally, we would say “total number of sugars per ounce” or “sugars per gram”. But, because of the way our measurements were taken, all we can say about this new variable is “sugars per unit of weight.”

Note that you must use the mutate() function from the tidyverse to add this variable to your dataframe. Then, using the same tidyverse pipe, calculate the average number of sugars per unit of weight using the variable you have created and assign that value to the variable sugars_weight_mean. Ensure that the provided code prints TRUE when you are finished.

## sugars_weight_mean <- cereal |>
##   mutate(sugars_weight = #...#) |>
##   summarize(mean_sugar_weight = #...#) |>
##   pull(mean_sugar_weight)

## all.equal(sugars_weight_mean, hw1_sol$sugars_weight_mean)

Part e (5 points)

Now repeat Part (d) but this time normalize by volume (i.e. “Sugars per cup”) rather than by weight. Call the name of the new column you create sugars_cup and store the calculated mean of column in the variable name sugars_cup_mean. As before, make sure that TRUE prints to the screen when you are finished.

## sugars_cup_mean <- cereal |>
##   mutate(sugars_cup = #...#) |>
##   summarize(mean_sugar_cup = #...#) |>
##   pull(mean_sugar_cup)

## all.equal(sugars_cup_mean, hw1_sol$sugars_cup_mean)

Part f (10 points)

Discuss: We now have three different estimates of the average added sugar content in box cereals: one by serving, one by weight, and one by volume (i.e. cup). Please identify at least one good thing (PRO) and one limitation (CON) for using each form of measurement.

Add your answer to each PRO: and CON: statement below. Note that you can create a “sub-bullet” by putting exactly two spaces before the - symbol, as shown below.

  • Regular Measurements
    • Pro:
    • Con:
  • Standardized by weight
    • Pro:
    • Con:
  • Standardized by Volume
    • Pro:
    • Con:

Part g (5 points)

Suppose that your friend eats exactly one bowl of cereal, filled to the brim, for breakfast. They are wanting to better understand how much sugar would be contained in each bowl of cereal if they were to switch brands. Based on this, which of the three variables (Sugars, sugars_weight, sugars_cup) would be the most appropriate variable to consider and why?

(Replace this text with your answer)

Problem 2 - Cereal Data: Grouped Operations (30 points)

This problem will continue to use the cereals data set. However, we will now be comparing the sugar content of different groups and subsets within the data. For this question, all data manipulations and summaries should be completed using tidyverse functions.

Part a (5 points)

For the first problem, we want to look at the mean added sugar content for the original servings for the different cereal manufacturers. Create a data frame named cereals_man that shows the group average/max/min sugar content per serving for all manufacturers that have at least five non-missing cereal types in the dataset. Arrange cereals_man using the average sugar content in descending order.

## cereals_man <- cereal |> 
##   filter(#...#) |> # remove rows with missing Sugar information
##   group_by(#...#) |> # group by Manufacturer
##   summarize(sugars_mean = #...#,
##            sugars_max = #...#,
##            sugars_min = #...#,
##            count = n()) |> # n() gives the size of each group
##  filter(#...#) |> # retain only manufacturers with at least 5 obs
##  arrange(desc(#...#)) # arrange by mean sugar content in descending order

## all.equal(cereals_man, hw1_sol[["cereals_man"]])

Part b (5 points)

Now repeat Part (a) but instead looking at the average sugar content per shelf, see Shelf variable, instead of Manufacturer. You will use the same variable names that you used in Part (a). See the hw1_sol[["cereals_shelf"]] dataframe to see how you should name the variables and arrange the rows. Your final answer should match the hw1_sol[["cereals_shelf"]] exactly.

# Adapt the code from the previous problem. This time using a 
# different grouping variable. 
## cereals_shelf <- #...#

## all.equal(cereals_shelf, hw1_sol[["cereals_shelf"]])

Part c (5 points)

Discuss What interesting observations can you make about the grouped sugar content averages/max/min? Identify at least three different things of interest to you. For at least one thing that you identify, provide a possible reason for the observation (there is no way to “know” with the information that we have).

  • Observation 1:
  • Observation 2:
  • Observation 3:

Part d (5 points)

Suppose you are participating in a competition where you will be required to eat one pound of cereal blindfolded. You do not get to pick the cereal, but you DO get to pick which shelf in the grocery store that the cereal box is selected from. Suppose that you are trying to limit your sodium content so that your ONLY goal with shelf selection is to minimize the worst-case (i.e., highest possible) scenario for sodium intake. Please identify (1) which variable form (sodium per serving, sodium per cup, sodium per unit weight) and (2) which variable summary (min, mean, or max) would be most appropriate in helping you make your shelf selection. No need for an explanation.

Answer: (Replace this text with your answer)

Part e (10 points)

Looking at the original cereal data, propose a grouped summary of a variable other than Sugars. You are welcome to group by Shelf, Manufacturer, or both Shelf and Manufacturer. In order to ensure reasonable estimates of the min/max/mean, you need to make sure that you only retain groups that have at least 5 non-missing observations of interest. To complete this problem, you must:

  • (2.5 points) Write a sentence explaining what grouped summary you plan to take and why you chose to summarize that variable. You should select one variable so summarize, and at least one variable to group by.

  • (5 points) Create a dataframe that contains the grouped summaries (min/max/mean) of that variable. Print this dataframe as part of your report (which can be done simply by putting the name of the dataframe on the last line of your code chunk).

  • (2.5 points) Describe at least one interesting feature of your grouped summary. Also provide a possible explanation for what might be causing the difference (or lack of difference) between the groups?

#...#

Answer:

(Replace this text with your explanation)

Submission Style (10 points)

Each submission should have the following elements:

  • You should submit the .qmd file (not the HTML rendering) with a file name in the style of <last_name>_<first_name>_homework1.qmd.

  • Your .qmd file 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, and styler. Note that you can ignore any flags with the tags: trailing_whitespace_linter, trailing_blank_lines_linter, and commented_code_linter.

Submission Checklist

© Copyright 2026, Susan Vanderplas

 
  • Report an issue