---
title: "Bakeoff Example"
output: html_document
date: "`r Sys.Date()`"
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

### Example: Bake-off

We will demonstrate using data from “The Great British Bake Off” compiled by [Allison Hill](https://www.apreshill.com/) in the R package `bakeoff`. The graphics that follow (and the code to produce the graphics) were lightly adapted from Allison’s [Plot Twist talk](https://www.apreshill.com/talk/2019-rladies-sydney/).

First, let’s decide on some questions we can address with this data.

1.  How did viewership change as new series came out?

2.  The show moved channels after Series 7. Was viewership higher, lower, or about the same before and after the move?

These questions have implicitly defined our *observations*: they are individual units of the most granular populations we are trying to describe or compare. Here, the populations to be compared are *series*, and units within them are *episodes*. The *variables* now fall into place: they are measured attributes of our observations (episodes): episode number, viewership, series membership, etc. This means that the following representation of viewership data is tidy for the “change in viewership over series” analysis:

```{r, message = F, warning= F}
# install.packages("bakeoff") #uncomment if not yet installed
library(bakeoff)
library(tidyverse)

ratings_tbl1 <- ratings %>% #save output to new tibble called ratings_tbl1
  mutate(ep_id = row_number()) %>% # create variable for episode number
  select(ep_id, viewers_7day, series, episode) #select specific columns

head(ratings_tbl1) #view first few rows of tibble
```

Every row is an observation (a unique episode), and the columns are variables (episode number across series, 7-day viewership, series, and episode number within series).

This is a typical example where the tidy format makes it easy to do our analysis. For example, to investigate these questions, we might make a bar plot of the number of viewers in millions within a 7-day window per episode, coloured by series. The following code uses the tidy tibble `ratings_tbl1` to make this bar plot. Notice that it was easy to use our graphing environment of choice (`ggplot2` in the tidyverse) to make the plot *because* our data is tidy, and the tidyverse is designed to work with tidy data.

```{r}
series_labels <- ratings_tbl1 %>% #save output to series_labels
  mutate(series=as.factor(series)) %>% #ensure series variable is a factor (categorical variable)
  group_by(series) %>% #group by series
  summarize(y_position = median(viewers_7day) + 1, # calculate positions for the bar charts
            x_position = mean(ep_id)) #

# make the plot
ratings_tbl1 %>% 
  mutate(series=as.factor(series)) %>% # ensure series is a factor variable
  ggplot(aes(x = ep_id, y = viewers_7day, fill = series)) + #set x and y axes, tell ggplot that we want things coloured by series
    geom_col(alpha = .9) + #tell ggplot we want a boxplot, change translucency with alpha
    ggtitle("7-Day Viewership across Series 1-10") + #add a title
    geom_text(data = series_labels, aes(label = series, #add text for series numbers
                                      x = x_position, 
                                      y = y_position)) +
    theme_classic() +  #add a classic theme
    scale_fill_manual(values = bakeoff_palette(),
                    guide = "none") + #set the colours so they aren't rainbow
    xlab("Episode Number") +  #add x axis label
    ylab("7-Day Viewership (millions)") #add y axis label
```

Now let’s consider a different set of questions:

1.  How did viewership grow between premiere to final episode in each series?

2.  Does the premiere-to-final-episode growth vary across series?

To investigate these questions, we might make a bar plot like the one below displaying percentage increase in the number of viewers in millions within a 7-day window from the premiere episode to finale episode for the first 10 series, using the tidy tibble `ratings_tbl2`:

```{r, echo = FALSE}
ratings_tbl2 <- ratings_tbl1 %>% 
  mutate(series=as.factor(series)) %>% 
  group_by(series) %>% 
  filter(episode == 1 | episode == max(episode)) %>% 
  ungroup() %>% 
  mutate(episode = recode(episode, `1` = "first", .default = "last")) %>%
  pivot_wider(id_cols=series, names_from=episode, values_from=viewers_7day)
```

```{r}
head(ratings_tbl2)
```

First, we can calculate the percentage change in viewership using `mutate()`:

```{r}
ratings_tbl2 <- ratings_tbl2 %>%  #overwrite original df so new variable saves
   mutate(pct_change = (last - first)/first) #calculate percent change

head(ratings_tbl2) #view first few rows of tibble
```

Then, we can visualize this using a bar chart:

```{r}
ratings_tbl2 %>% 
  ggplot(aes(x = fct_rev(series), y=pct_change)) + #initialize the plot
  geom_col(fill = bakeoff::bakeoff_colors("baltic"), alpha = .5) + #set bar chart with fill colours, semi-translucent 
  labs(x = "Series", y = "% Increase in Viewers, First to Last Episode") + #add x labels
  ggtitle("% Increase in Viewers from Premiere to Finale") + #add y labels
  scale_y_continuous(labels = scales::percent) + #change y axis to percentage 
  theme_classic() + #add classic theme
  coord_flip() #flip horizontallyz
```

::: {.callout-warning icon="false" appearance="minimal"}
### Exercise 

With a partner or a small group discuss if you could you have calculated the information in `ratings_tbl2` using `ratings_tbl1`? (No need to write code - just discuss whether it’s possible.)
:::

### **Pivoting Wider**

Here is some code to create a variable for whether an episode is the first or last episode of the season to `ratings_tbl1` and subset to only the data from the first and last episodes of each season.

```{r}
ratings_tbl1 <- ratings_tbl1 %>% #overwrite ratings_tbl1
 group_by(series) %>% #group by series
  filter(episode == 1 | episode == max(episode)) %>% #get only the first and last episodes
  ungroup() %>% #ungroup the data
  mutate(episode_fl = recode(episode, `1` = "first", .default = "last")) #add a new variable indicatign whether or not the episode was first or last, and recode the variable to "first" or "last"

head(ratings_tbl1)
```

This is not the same format as `ratings_tbl2`, which was the tidy format for our earlier “viewership growth within series” analysis. But it does contain the same information. To finish converting `ratings_tbl1` into `ratings_tbl2`, we need to make `ratings_tbl1` *wider*: we need to move some information in the rows (the info about whether each episode is the first or last episode of each season) into new columns.

We can solve this problem using `pivot_wider`, which needs three pieces of information.

-   What is a set of columns that uniquely identifies each observation? Put their names in the `id_cols` argument.

-   Where should the names for the new columns come from? Put the name of the column you want to take the new variable names from in the `names_from` argument.

-   What values should the new columns contain? Put the name of the columns you want to take the values from to `values_from` in the `values_from` argument.

Note that if you don’t specify an `id_cols` argument, `pivot_wider` will assume that you want it to be every column except those in `names_from` and `values_from`.

```{r}
ratings_tbl2 <- ratings_tbl1 %>% #overwrite ratings_tbl2
  pivot_wider(id_cols = series, #pivot with id as series
              names_from=episode_fl, #get column names from episode_fl
              values_from=viewers_7day) #fill in values form viewers_7day

head(ratings_tbl2)
```

Also note that any columns not included in `id_cols`, `names_from`, and `values_from` (e.g., `ep_id`) will simply be dropped.

If we wanted to keep the info in `ep_id` as well, we would add it to the `values_from` argument:

```{r}
ratings_tbl1 %>% 
  pivot_wider(id_cols = series, 
              names_from=episode_fl, 
              values_from=c(viewers_7day, ep_id)) #now including ep_id in the values_from call to include it in the output
```

### 
