---
title: "Week 3: Class Notes"
format: html
embed-resources: true
---

```{r}
#| label: setup
#| message: false
#| echo: false

library(tidyverse)
library(liver)
```

## Cereal Data

This cereal dataset is part of the `liver` package.

```{r}
data(cereal)
head(cereal)
```

# Tuesday

## Wrangle / Manipulate / Tidy Data

For the following, write a game plan or describe in words steps you would take from `cereal` data to get the output.

1. What is the ratio of fiber to sugars in each cereal?

2. Create a new dataset that only has Nabisco cereals and displays the protein, fat, and sodium in each.

3. Create a table that shows, for each manufacturer the average and standard deviation of the grams of sugar in their cereals, along with how many cereals are in the data for each manufacturer. Order the table from most sugar (on average) to least.


## `dplyr` verbs

+ `filter()`  
+ `arrange()` 
+ `select()` 
+ `mutate()` 
+ `summarize()` 
+ `group_by()` 


## pipe operator

Change: `Tools` > `Global Options...` > `Code` > check `Use native pipe operator` box to use keyboard shortcut:
      + `ctrl/cmd` + `shift` + `m`

```{r}
head(cereal)
```

```{r}
cereal |> 
  head()
```

## `filter()`

```{r}
cereal |> 
  filter(sugars < 5,
         type == "hot")
```


```{r}
cereal |> 
  filter(name %in% c("Cheerios", "Cinnamon Toast Crunch", 
                     "Raisin Bran", "Cracklin' Oat Bran"))
```


```{r}
cereal |> 
  slice_head(n = 5)
```

## `arrange()`

```{r}
cereal |> 
  arrange(sodium)
```


```{r}
cereal |> 
  arrange(sodium, sugars)
```

## `slice_min()` / `slice_max()`

```{r}
cereal |> 
  slice_max(order_by = sugars, n = 3)
```

```{r}
cereal |> 
  slice_max(order_by = sugars, n = 3, 
            with_ties = FALSE)
```


## `select()`

```{r}
cereal |> 
  select(name, manuf, calories, cups)
```

```{r}
cereal |> 
  select(name:calories)
```


```{r}
cereal |> 
  select(-rating)
```


```{r}
cereal |> 
  select(name, rating, manuf, type, calories, cups, weight,
         everything())
```


```{r}
cereal |> 
  select(name, starts_with("c"))
```


```{r}
cereal |> 
  select(name, where(is.numeric))
```


If you just want to rename a variable, use `rename()`
```{r}
cereal |> 
  rename(temp = type)
```

If you want to rename variables and then only select some variables, use `select()`

```{r}
cereal |> 
  select(name,
         temp = type,
         cons_rating = rating)
```

## `mutate()`

```{r}
cereal |> 
  mutate(potass_per_cup = potass / cups)
```

```{r}
cereal |> 
  mutate(shelf = as.factor(shelf))
```


## `summarize()`

```{r}
cereal |> 
  summarise(mean_fiber = mean(fiber))
```

```{r}
cereal |> 
  summarise(mean_fiber = mean(fiber),
          num_cereals = n(),
          mean_sugar = mean(sugars))
```

## `group_by()`

```{r}
cereal |> 
  group_by(manuf)
```

```{r}
cereal |> 
  group_by(manuf) |> 
  summarise(mean_sugar = mean(sugars))
```


```{r}
cereal |> 
  group_by(manuf) |> 
  mutate(mean_sugar = mean(sugars))
```


### Quick Check

How many rows and columns will each of these data frames have? (Try to figure this out before running the code)

```{r}
cereal |> 
  group_by(manuf) |> 
  mutate(fiber_carb_rat = mean(fiber / carbo))
```


```{r}
cereal |> 
  group_by(manuf) |> 
  summarize(fiber_carb_rat = mean(fiber / carbo))
```


`ungroup()`

```{r}
cereal |> 
  group_by(manuf) |> 
  summarize(fiber_carb_rat = mean(fiber / carbo)) |> 
  ungroup()
```


## Glue it all together

Sometimes you just want to show a table

```{r}
cereal |> 
  filter(type == "cold") |> 
  mutate(potass_per_cup = potass / cups) |> 
  group_by(manuf) |> 
  summarise(mean_potass_per_cup = mean(potass_per_cup))
```

Other times, you will want to save your wrangled data for later.

```{r}
cereal_summary <- cereal |> 
  filter(type == "cold") |> 
  mutate(potass_per_cup = potass / cups) |> 
  group_by(manuf) |> 
  summarise(mean_potass_per_cup = mean(potass_per_cup))
```

### Now you!

Implement the `dplyr` pipelines to address the three questions from the beginning of class


1. What is the ratio of fiber to sugars in each cereal?

```{r}

```

2. Create a new dataset that only has Nabisco cereals and displays the protein, fat, and sodium in each.

```{r}

```

3. Create a table that shows, for each manufacturer the average and standard deviation of the grams of sugar in their cereals, along with how many cereals are in the data for each manufacturer. Order the table from most sugar (on average) to least.

```{r}

```

# Thursday

## `pull()`

```{r}
cereal |> 
  filter(type == "cold") |> 
  pull(potass) |> 
  mean(na.rm = T)
```

Using `pull()` would fix the issue with Check-In 3.1 Q8:

```{r}
penguins |> 
  filter(species == "Adelie") |> 
  pull(body_mass_g) |> 
  mean(na.rm = T)
```


## Frequency tables

```{r}
cereal |> 
  group_by(manuf) |> 
  summarize(n = n())
```

```{r}
cereal |> 
  group_by(manuf) |> 
  count()
```


## `if_else()` & `case_when()`

```{r}
cereal |> 
  mutate(po_category = if_else(potass <= 100, 
                               "low", 
                               "high"),
         .after = potass)
```


```{r}
cereal |> 
  mutate(sugar_level = case_when(sugars == -1 ~ NA_character_,
                                 sugars < 2   ~ "low",
                                 sugars < 5   ~ "medium",
                                 sugars < 10  ~ "high",
                                 TRUE         ~ "very high")) |> 
  select(name, sugars, sugar_level)
```

## More `slice()`

**For each manufacturer,** find the cereal with the most fiber:

```{r}
cereal |> 
  group_by(manuf) |> 
  slice_max(order_by = fiber)
```


Find the 3 cereals with the highest fiber and potassium.

```{r}
cereal |> 
  slice_max(order_by = data.frame(fiber, potass),
            n = 3)
```


## `across()`

```{r}
cereal |> 
  group_by(type) |> 
  summarise(across(.cols = calories:potass, 
                   .fns = ~ mean(.x, na.rm = T)))
```

```{r}
cereal |> 
  group_by(type) |> 
  summarise(across(.cols = where(is.numeric),
                   .fns = ~ mean(.x, na.rm = T)))
```


## `if_any()` / `if_all()`

```{r}
colleges <- read_csv("https://www.dropbox.com/s/bt5hvctdevhbq6j/colleges.csv?dl=1")

colleges_clean <- colleges |> 
    select(INSTNM, CITY, STABBR, ZIP,
         ADM_RATE, SAT_AVG, UGDS,
         TUITIONFEE_IN, TUITIONFEE_OUT,
         CONTROL, REGION) |> 
  filter(CONTROL == 1 | CONTROL == 2)
```

```{r}
colleges_clean |> 
  filter(if_any(.cols = ADM_RATE:TUITIONFEE_OUT, 
                 .fns = ~ .x == "NULL")) 
```

```{r}
colleges <- read_csv("https://www.dropbox.com/s/bt5hvctdevhbq6j/colleges.csv?dl=1",
                     na = c("", "NA"))
```

## Practice!

How would you make this plot from the diamonds dataset in ggplot2?

```{r}

```


## `kable()`

```{r}
library(knitr)
```

```{r}
cereal_clean <- cereal |> 
  mutate(ratio = sugars / potass)
  
cereal_clean |> 
  slice_head(n = 3) |> 
  kable()
```

