Skip to content

Instantly share code, notes, and snippets.

@lashlee
Created March 5, 2020 01:22
Show Gist options
  • Save lashlee/83a464026796edd213b0b28511e20704 to your computer and use it in GitHub Desktop.
Save lashlee/83a464026796edd213b0b28511e20704 to your computer and use it in GitHub Desktop.
Calculate Super Tuesday delegate results with Politico data.
# Setup -------------------------------------------------------------------
library(htmltab)
library(dplyr)
library(tidyr)
library(ggplot2)
url <- 'https://www.politico.com/2020-election/results/super-tuesday/'
# Parse -------------------------------------------------------------------
raw_tab <- htmltab::htmltab(
doc = url,
which = 1,
header = c(1, 2)
)
tab <-
raw_tab %>%
na.omit() %>%
extract(
col = Called,
into = c('state_name', 'state_prize', 'state', 'reporting_share'),
regex = '(\\D*)([:digit:]{2,3})[:space:]del\\.([:alpha:]{2})([:digit:]{2,3}%)'
) %>%
mutate(state_prize = as.integer(state_prize)) %>%
mutate_at(
.vars = c('Biden', 'Sanders', 'Bloomberg', 'Warren'),
.funs = function(pct) as.numeric(sub("%", "", pct))
) %>%
mutate_at(
.vars = c('Biden', 'Sanders', 'Bloomberg', 'Warren'),
.funs = list(
viable = function(col) if_else(col >= 15, col, 0)
)
) %>%
mutate(
viable_share = Biden_viable + Sanders_viable + Bloomberg_viable + Warren_viable,
Biden_delegates = floor(state_prize * Biden_viable / viable_share),
Sanders_delegates = floor(state_prize * Sanders_viable / viable_share),
Bloomberg_delegates = floor(state_prize * Bloomberg_viable / viable_share),
Warren_delegates = floor(state_prize * Warren_viable / viable_share)
) %>%
select(
state,
reporting_share,
state_prize,
Biden_delegates,
Sanders_delegates,
Bloomberg_delegates,
Warren_delegates
)
# Results -----------------------------------------------------------------
knitr::kable(tab)
# Results by State
# |state |reporting_share | state_prize| Biden_delegates| Sanders_delegates| Bloomberg_delegates| Warren_delegates|
# |:-----|:---------------|-----------:|---------------:|-----------------:|-------------------:|----------------:|
# |AL |100% | 52| 41| 10| 0| 0|
# |VA |100% | 99| 69| 29| 0| 0|
# |NC |100% | 110| 70| 39| 0| 0|
# |TN |98% | 64| 32| 19| 12| 0|
# |AR |100% | 31| 15| 8| 6| 0|
# |OK |100% | 37| 22| 14| 0| 0|
# |MN |100% | 75| 34| 26| 0| 13|
# |TX |100% | 228| 121| 106| 0| 0|
# |ME |94% | 24| 9| 9| 0| 4|
# |MA |100% | 91| 37| 29| 0| 23|
# |VT |100% | 16| 4| 11| 0| 0|
# |CO |70% | 67| 15| 24| 14| 11|
# |UT |73% | 29| 5| 11| 5| 5|
# |CA |84% | 415| 176| 238| 0| 0|
tab %>%
select(ends_with('_delegates')) %>%
summarize_all(sum) %>%
knitr::kable()
# Results Overall
# | Biden_delegates| Sanders_delegates| Bloomberg_delegates| Warren_delegates|
# |---------------:|-----------------:|-------------------:|----------------:|
# | 650| 573| 37| 56|
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment