---
title: "Homework 1 - STAT 1080"
author: "(Put Name Here)"
editor: source
format: 
  html:
    self-contained: true
execute:
  echo: true   # show code by default
  warning: false
  message: false
---

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

```{r}
library(tidyverse)
library(stat1080r)

head(cereal)
```

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

```{r}
glimpse(cereal)
```

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

<!-- Part 1a Answer -->

```{r}
## sugar_mean_1 <- cereal |>
##   summarize(tmean = #...#) |>
##   pull(tmean)

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

<!-- End Part 1a Answer -->

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

::: {.callout-note collapse=true}

### Math 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`).

::: {.callout-note collapse=true}

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

<!-- Part 1b Answer -->

```{r}
## sugar_mean_2 <- cereal |>
##   summarize(tmean = #...#) |>
##   pull(tmean)

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

<!-- End Part 1b Answer -->


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

<!-- Part 1c Answer -->

```{r}
weight_u <- cereal |> 
  pull(Weight) |>
  unique()

## cups_u <- #...#

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

<!-- End Part 1c Answer -->

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

<!-- Part 1d Answer -->

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

<!-- End Part 1d Answer -->

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

<!-- Part 1e Answer -->

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

<!-- End Part 1e Answer -->

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

<!-- Part 1f Answer -->

- Regular Measurements
  - **Pro:** 
  - **Con:** 
  
- Standardized by weight
  - **Pro:** 
  - **Con:** 
  
- Standardized by Volume
  - **Pro:** 
  - **Con:** 

<!-- End Part 1f Answer -->

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

<!-- Part 1g Answer -->

(Replace this text with your answer)

<!-- End Part 1g 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. 

<!-- Part 2a Answer -->

```{r}
## 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"]])
```

<!-- End Part 2a Answer -->

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

<!-- Part 2b Answer -->

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

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

<!-- End Part 2b Answer -->

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

<!-- Part 2c Answer -->

- **Observation 1:** 
- **Observation 2:** 
- **Observation 3:** 

<!-- End Part 2c Answer -->

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

<!-- Part 2d Answer -->
**Answer:** (Replace this text with your answer)


<!-- End Part 2d 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? 


<!-- Part 2e Answer -->

```{r}
#...#
```

**Answer:** 

(Replace this text with your explanation)

<!-- End Part 2e Answer -->

# 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

- [ ] Check your filename -- is it of the form `lastname_firstname_homework01.qmd`?

- [ ] Check the author (specified around line 3 of this file) -- is your name there?

- [ ] Render your file using the blue arrow at the top of the RStudio text editor window.
    - [ ] If your file does not render, address any errors in the code leading to failure.
    
- [ ] Preview your rendered file in a browser. Do all of your answers show up the way you expected them to?    
If the answers do not show up the way you want them, check your markdown formatting against the cheat sheet in RStudio (Help -> Cheat Sheets -> Rmarkdown cheat sheets)

- [ ] Run the `lintr` style checks (Canvas -> Course homepage -> Style Guides link under USU picture)
    - [ ] Switch to source mode in RStudio
    - [ ] Addins -> Style active file
    - [ ] Addins -> Lint current file
    - [ ] Address any issues that the lint command raises

- [ ] Render your file again, to check that the `styler` and `lintr` addons didn't mess up any formatting. 

- [ ] Upload your **qmd** file (NOT the html file) to Canvas

- [ ] Double-check your submission - is the file you uploaded the one you want to be graded?