Data analysis of New Zealand General Election advanced voting patterns 2002-2017

votingpatterns.R 1.6KB

1234567891011121314151617181920212223242526272829303132333435
  1. library(dplyr)
  2. library(tidyr)
  3. dat <- read.csv("AdvancedVotesNewZealand.csv", stringsAsFactors = FALSE) %>%
  4. mutate(Party = gsub(" $", "", Party),
  5. Party = gsub("Mâori", "Māori", Party)) %>%
  6. pivot_wider(id_cols = c(Year, Party), names_from = Type, values_from = c(Votes, Seats)) %>%
  7. mutate(Votes_Other = Votes_Total - Votes_Advance,
  8. Advance_Proportion = Votes_Other / Votes_Total,
  9. Seat_Difference = Seats_Advance - Seats_Total)
  10. elec <- dat %>% group_by(Year) %>%
  11. summarise(Total_Votes = sum(Votes_Total),
  12. Total_Advance = sum(Votes_Advance),
  13. Total_Other = sum(Votes_Other),
  14. Total_Seats = sum(Seats_Total),
  15. Advance_Seats = sum(Seats_Advance),
  16. Seat_Differences = sum(abs(Seat_Difference)),
  17. .groups = "drop") %>%
  18. mutate(Prop_Advance = Total_Advance / Total_Other)
  19. partylev <- dat %>% left_join(elec, by = "Year") %>%
  20. mutate(PV_Prop_Total = Votes_Total / Total_Votes,
  21. PV_Prop_Advance = Votes_Advance / Total_Advance)
  22. partyav <- partylev %>% group_by(Party) %>%
  23. summarise(Total_Mean_Prop = mean(PV_Prop_Total),
  24. Advance_Mean_Prop = mean(PV_Prop_Advance),
  25. .groups = "drop") %>% arrange(desc(Total_Mean_Prop))
  26. partylev %>% select(Year:Party, Votes_Advance, Votes_Other, Seats_Advance, Seats_Total, PV_Prop_Advance, PV_Prop_Total) %>%
  27. pivot_longer(cols = Votes_Advance:PV_Prop_Total,
  28. names_to = c("Quantity", "Type"),
  29. names_pattern = "(.*)_([^_]*)$",
  30. values_to = "value") %>%
  31. pivot_wider(names_from = "Quantity", values_from = "value") %>% drop_na()