Skip to content

Instantly share code, notes, and snippets.

@reuning
Last active April 23, 2024 16:33
Show Gist options
  • Save reuning/4d2b6d984cf03610bbd31287e86dc5fd to your computer and use it in GitHub Desktop.
Save reuning/4d2b6d984cf03610bbd31287e86dc5fd to your computer and use it in GitHub Desktop.
Calculates state level Cook PVI using their current weighting.
library(tidyverse)
## Data from: https://dataverse.harvard.edu/dataset.xhtml?persistentId=doi%3A10.7910%2FDVN%2F42MVDX
df <- read_csv("1976-2020-president.csv")
cook_pvi <- df |> filter(party_simplified%in% c("DEMOCRAT", "REPUBLICAN")) |>
select(year, state, party_simplified, candidatevotes) |>
pivot_wider(id_cols=c(year,state),
names_from = party_simplified,
values_from=candidatevotes, values_fn=sum) |>
mutate(percent = DEMOCRAT/(DEMOCRAT+REPUBLICAN)*100) |>
group_by(year) |>
mutate(national_percentage = sum(DEMOCRAT)/sum(DEMOCRAT+REPUBLICAN)*100) |>
mutate(lean = percent-national_percentage) |>
select(year, state, lean) |>
group_by(state) |>
mutate(pvi = (lean*3/4 + lag(lean)/4)) |>
complete(year=full_seq(year, 2)) |>
fill(pvi, .direction="down") |>
mutate(year=year + 2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment