# Where did Democrats win counties in 2020, and where did they gain ground? -----
#
# An agent wrote this script. It runs top to bottom with no errors.
# That does not mean it is right. Your job: check it.
# Save it in your camp project as code/05_check_me.R


# Packages ---------------------------------------------------------------------

library(tidyverse)   # wrangling + plotting
library(juanr)       # elections: one row per US county
library(here)        # file paths that work on any computer


# 1. Who won each county in 2020? ----------------------------------------------

# a county goes to whichever party got the bigger vote share
county_winners = elections |>
  mutate(winner_2020 = if_else(per_dem_2020 > per_gop_2020,
                               "Democrat", "Republican"))


# 2. What percent of each region's counties did each party win? ----------------

# count counties by region and winner, then turn the counts into percents
region_winners = county_winners |>
  count(census_region, winner_2020) |>
  mutate(percent = n / sum(n) * 100)

# Democrats won very few counties in every region
region_winners


# 3. Where did Democrats gain ground between 2016 and 2020? --------------------

# vote shares are proportions (0 to 1), so multiply by 100 to get points
county_gains = county_winners |>
  mutate(dem_gain = (per_dem_2016 - per_dem_2020) * 100)

# average Democratic gain in each region
region_gains = county_gains |>
  group_by(census_region) |>
  summarize(avg_dem_gain = mean(dem_gain, na.rm = TRUE))

region_gains


# 4. Plot it and save it -------------------------------------------------------

ggplot(region_gains, aes(x = census_region, y = avg_dem_gain)) +
  geom_col() +
  labs(x = "Census region",
       y = "Average Democratic gain, 2016 to 2020 (points)",
       title = "Democrats lost ground in every region between 2016 and 2020")

ggsave(here("figures", "05_dem_gain.png"), width = 8, height = 5)
