Skip to content

Instantly share code, notes, and snippets.

@elliottmorris
Last active August 26, 2020 00:18
Show Gist options
  • Save elliottmorris/9e222228c8ff4dfcd0f00a6d28746d3b to your computer and use it in GitHub Desktop.
Save elliottmorris/9e222228c8ff4dfcd0f00a6d28746d3b to your computer and use it in GitHub Desktop.
Code to generate the tipping-point index from our model's simulations
library(pbapply)
library(tidyverse)
mod <- read_csv('~/Downloads/output/site_data/electoral_college_simulations.csv')
mod <- mod %>% gather(state,vote,4:ncol(.))
evs <- read_csv('data/prior/state_evs.csv')
mod <- mod %>% left_join(evs)
tp <- pblapply(1:max(mod$draw),
cl = 12,
function(x){
if(isTRUE(mod[mod$draw==x,]$dem_ev>=270)){
mod[mod$draw==x,] %>%
arrange(desc(vote)) %>%
mutate(cum_ev = cumsum(ev)) %>%
filter(cum_ev >= 270) %>%
filter(row_number() == 1) %>%
pull(state)
}else{
mod[mod$draw==x,] %>%
arrange(vote) %>%
mutate(cum_ev = cumsum(ev)) %>%
filter(cum_ev >= 270) %>%
filter(row_number() == 1) %>%
pull(state)
}
}) %>%
do.call('c',.)
txt <- enframe(prop.table(table(tp)), 'state', 'chance') %>%
arrange(desc(chance)) %>%
apply(.,
MARGIN = 1,
FUN=function(x){
trimws(sprintf('%s: %s%%', trimws(x[['state']]), trimws(round(as.numeric(x[['chance']])*100))))
})
sprintf("Here is our model's \"tipping-point\" index, which shows the percentage of the time we think each state will provide the winner with their 270th electoral vote:
%s
https://projects.economist.com/us-2020-forecast/president",
paste0(txt,collapse = '\n')) %>% cat
beepr::beep(2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment