library(tidyverse)
library(rvest)
URL <- "https://history.house.gov/Institution/Party-Divisions/Party-Divisions/"
webpage <- read_html(URL)
cong <- as_tibble(html_table(webpage)[[1]])
onms <- colnames(cong)
newnms <- c("congress", "seats", "D", "R", "other", "delres")
cong <- cong %>%
slice((which(grepl("^Republican", `Anti-Administration`))[1] + 1):nrow(.)) %>%
filter(`Congress (Years)` != colnames(cong)[1]) %>%
mutate(year = gsub("(*.*-)|(*.*–)|)|)2", "", `Congress (Years)`)) %>%
mutate(year = as.numeric(year) - 2) %>%
rename_at(vars(onms), ~newnms) %>% select(-other, -delres) %>%
mutate(seats = substr(seats, 1, 3)) %>%
mutate_at(.vars = vars(seats, D, R), as.numeric) %>%
mutate(swing = (D - R) / (D + R))
cong %>%
ggplot() + geom_line(aes(year, swing)) +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5)) +
geom_hline(yintercept = 0, lty = 2, col = "red") +
xlab("") + ylab("(D - R) / (D + R)") +
ggtitle("Normalized Party Control Index for US House") + theme_linedraw() +
scale_x_continuous(breaks = seq(1859, 2019, 10), expand = c(0, 2))