Skip to content

Instantly share code, notes, and snippets.

@reuning
Created February 7, 2020 03:00
Show Gist options
  • Save reuning/aadb9d54072c08436d6eb45fdbee3a4f to your computer and use it in GitHub Desktop.
Save reuning/aadb9d54072c08436d6eb45fdbee3a4f to your computer and use it in GitHub Desktop.
library(rvest)
library(magrittr)
tmp <- read_html("https://results.thecaucuses.org/")
full <- tmp %>% html_nodes("ul.thead") %>% html_nodes("li") %>% html_text()
sub <- tmp %>% html_nodes("ul.sub-head") %>% html_nodes("li") %>% html_text()
full <- full[-1:-2]
sub <- sub[-1:-2]
counties <- tmp %>% html_nodes('div.precinct-rows')
out <- NULL
for(ii in 1:length(counties)){
count_tmp <- counties[ii] %>% html_nodes('div.precinct-county') %>%
html_text()
prec <- counties[ii] %>% html_nodes('div.precinct-data') %>%
html_nodes('ul')
tmp_out <- NULL
for(jj in 1:(length(prec)-1)){
tmp_out <- rbind(tmp_out, prec[jj] %>% html_nodes('li') %>% html_text())
}
tmp_trans <- rbind(tmp_out[,2:4], tmp_out[,5:7],
tmp_out[,8:10], tmp_out[,11:13],
tmp_out[,14:16], tmp_out[,17:19],
tmp_out[,20:22], tmp_out[,23:25],
tmp_out[,26:28], tmp_out[,29:31],
tmp_out[,32:34], tmp_out[,35:37],
tmp_out[,38:40], tmp_out[,41:43])
tmp_trans <- as.data.frame(apply(tmp_trans, 2, as.numeric))
tmp_trans$prec <- rep(tmp_out[,1], times=14)
tmp_trans$cand <- c(sapply(full[full!=""], rep, times=nrow(tmp_out)))
tmp_trans$county <- count_tmp
out <- rbind(out, tmp_trans)
}
names(out)[1:3] <-c('First', 'Final', 'SDE')
ggplot(out[!out$cand %in% c('Bennet', 'Bloomberg', 'Delaney',
'Gabbard', 'Other', 'Patrick', 'Steyer'),],
aes(x=Final-First, y=First)) + geom_point() +
facet_wrap(~cand) + theme_minimal()
out$Change <- out$Final - out$First
tmp <- reshape2::dcast(out, county+prec~cand, value.var='Change')
library(GGally)
my_bin <- function(data, mapping, ..., low = "gray", high = "orangered2") {
ggplot(data = data, mapping = mapping) +
geom_bin2d(..., bins=20) +
scale_fill_gradient(low = low, high = high) +
geom_hline(yintercept = 0, linetype='dashed') +
geom_vline(xintercept = 0, linetype='dashed')
}
p <- ggpairs(tmp[,c("Biden", "Buttigieg", "Klobuchar",
"Sanders", "Warren", "Yang", "Uncommitted")],
diag = list(continuous='barDiag'),
lower=list(continuous=my_bin))
p + theme_minimal() +
ggtitle('Change in Candidate Support in Each Precinct')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment