Created
December 16, 2019 04:58
-
-
Save chrishanretty/42a029fd9ea2eba8dc266c3d6339cec2 to your computer and use it in GitHub Desktop.
Longest spell of increasing vote share in national elections
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(tidyverse) | |
longest_increase <- function(sign_d) { | |
rles <- rle(sign_d) | |
rle_values <- rles$value | |
rle_lengths <- rles$length | |
rle_lengths <- rle_lengths[which(rle_values == 1)] | |
rle_values <- rle_values[which(rle_values == 1)] | |
max(rle_lengths) | |
} | |
elex <- read.csv("view_election.csv") | |
elex <- elex %>% | |
filter(election_type == "parliament") %>% | |
mutate(election_date = as.Date(election_date)) | |
foo <- elex %>% | |
dplyr::select(party_id, party_name_english, | |
country_name_short, election_date, vote_share) %>% | |
group_by(country_name_short, party_id, party_name_english) %>% | |
arrange(election_date) %>% | |
mutate(delta = c(NA, diff(vote_share)), | |
sign_d = sign(delta)) %>% | |
summarize(longest_spell = longest_increase(sign_d)) | |
foo %>% | |
arrange(desc(longest_spell)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment