library(knitr)
opts_chunk$set(fig.width = 6,
                      fig.height = 4,
                      fig.align='center',
                      dev = "png",
                      warning = FALSE,
                      message = FALSE)

Introduction

eechidna (Exploring Election and Census Highly Informative Data Nationally for Australia) is an R package that makes it easy to look at the data from Australian Census and Federal Elections from 2001 to 2016.

This vignette documents how to access the data from the 2016 Federal Election (House of Representatives: first preferences, two party preferred and two candidate preferred votes). We obtained these data from http://results.aec.gov.au/. This package incorporates data that is copyright Commonwealth of Australia (Australian Electoral Commission).

In this vignette we show a few typical methods to explore the data, inspired by Peter Ellis's work on NZ election data.

2016 Federal Election House of Representatives data

Electorates

In the eechidna package we have three datasets for each election, summarised here:

Data object name | Description ----------------------- | ------------------------------------------------------------ fp16 | first preference votes for candidates at each electorate (2016) tpp16 | two party preferred votes for candidates at each electorate (2016) tcp16 | two condidate preferred votes for candidates at each electorate (2016)

The suffix 16 corresponds with the 2016 federal election, so objects for other elections will have an equivalent suffix, e.g. fp07 contains first preference votes for candidates in each electorate from the 2007 federal election.

We can access and explore each of these using common methods in R, for example:

library(eechidna)
library(tidyverse)
library(purrr)
library(knitr)
library(broom)
library(purrrlyr)

data(fp16)
data(tpp16)
data(tcp16)
data(abs2016)

# inspect the data frame
glimpse(fp16)
# show the first few rows
head(fp16) %>% knitr::kable()

We can see that the data contains r formatC(nrow(fp16), big.mark=",", drop0trailing=TRUE, format="f") rows and r ncol(fp16) columns. Each of the six data objects can be accessed and inspected in this way. Note that some parties have slightly different names in different states. We've simplified the data by renaming some of the parties to the varient of the name that won the most votes.

Polling booths

The same three voting measures are also available for each polling booth, of which there are over 7,000 in each election. These can be downloaded from github using the firstpref_pollingbooth_download, twoparty_pollingbooth_download and twocand_pollingbooth_download functions, which contain all results from 2001-2016 elections. In these datasets, the variable year represents the election year, so an individual years' polling booth data can be easily obtained using filter from the dplyr package.

Exploring the election results

Which party won the election?

We can summarise the data to discover some basic details about the election. Let's start by reproducing the overall result of the election by finding out which party won the most electorates according to the two candidate preferred votes:

who_won <- tcp16 %>% 
  filter(Elected == "Y") %>% 
  group_by(PartyNm) %>% 
  tally() %>% 
  arrange(desc(n)) 

# inspect
who_won %>% 
  kable()

# plot
library(scales)
ggplot(who_won, 
       aes(reorder(PartyNm, n), 
           n)) +
  geom_point(size = 2) + 
  coord_flip() + 
  scale_y_continuous(labels = comma) +
  theme_bw() +
  ylab("Total number of electorates") +
  xlab("Party") +
  theme(text = element_text(size=10))

This result above matches the official AEC result, showing the Liberal party winning the most electorates (76).

Which party received the most ordinary votes?

An alternative way to evaluate the outcome of the election is by counting the number of ordinary first preference votes for each party (not including postal votes, preference flows, etc.). Here we can find the total number of ordinary votes for each party:

total_votes_for_parties <- fp16 %>% 
  select(PartyNm, OrdinaryVotes) %>% 
  group_by(PartyNm) %>% 
  dplyr::summarise(total_votes = sum(OrdinaryVotes, rm.na = TRUE)) %>% 
  ungroup() %>%
  arrange(desc(total_votes))

#  inspect
total_votes_for_parties %>% 
  head %>% # just the first 10 rows
  kable

The table above shows a similar result, with the Liberal Party recieving the most ordinary votes.

We can plot the ordinary vote count like so:

ggplot(total_votes_for_parties, 
       aes(reorder(PartyNm, total_votes), 
           total_votes)) +
  geom_point(size = 2) + 
  coord_flip() + 
  scale_y_continuous(labels = comma) +
  theme_bw() +
  ylab("Total ordinary votes") +
  xlab("Party") +
  theme(text = element_text(size=10))

Which candidate did the best?

There are a few ways we can answer this question. We can see who received the highest number of ordinary votes, like this:

who_most_votes <- fp16 %>% 
  filter(CandidateID != 999) %>% #exclude informal votes
  mutate(candidate_full_name = paste0(GivenNm, " ", Surname, " (", CandidateID, ")")) %>% 
  group_by(candidate_full_name) %>% 
  dplyr::summarise(total_votes_for_candidate = sum(OrdinaryVotes, rm.na = TRUE)) %>% 
  arrange(desc(total_votes_for_candidate))
# inspect
who_most_votes %>% 
  mutate(total_votes_for_candidate = 
           prettyNum(total_votes_for_candidate, 
                     big.mark = ","))  %>% 
  head %>% 
  kable

But this is a crude measure of how successful a candidate was in the election, because electorates with more people will result in more votes for the winner, even if the victory is only by a tiny margin. So let's remove the effect of the population size in the electorates by finding out who won the highest proportion of first preference votes in their electorate.

who_most_votes_prop <- fp16 %>% 
  filter(CandidateID != 999) %>% #exclude informal votes
  mutate(candidate_full_name = paste0(GivenNm, " ", Surname, " (", CandidateID, ")")) %>% 
  group_by(candidate_full_name) %>% 
  dplyr::summarise(total_votes_for_candidate = sum(Percent, rm.na = TRUE)) %>% 
  arrange(desc(total_votes_for_candidate)) %>% 
  dplyr::rename(percent_votes_for_candidate = total_votes_for_candidate)
# inspect
who_most_votes_prop %>% 
  mutate(percent_votes_for_candidate = 
           prettyNum(percent_votes_for_candidate, 
                     big.mark = ","))  %>% 
  head %>% 
  kable

In the above table (which shows just the first ten rows for convienience) we see that Julie Bishop received the highest proportion of first preference votes in any electorate, as well as a few more familiar names doing very well in their electorates. We can see that taking about 65% of the first preference vote in an electorate counts as a huge win. But what about who won with the least amount of first preference votes?

Which candidate won with the smallest percentage of votes?

who_won_least_votes_prop <- fp16 %>% 
  filter(Elected == "Y") %>% 
  arrange(Percent) %>% 
  mutate(candidate_full_name = paste0(GivenNm, " ", Surname, " (", CandidateID, ")")) %>% 
  select(candidate_full_name, PartyNm, DivisionNm, Percent)

who_won_least_votes_prop %>% head %>% kable

Michael Danby won Melbourne Ports with just 27% of first preference votes.

How about the smallest winning margin that occured in the 2016 election? Let's find the candidates who won their electorate by the slimmest advantage over their competitors, meaning the smallest difference between two candidate preferred votes.

Which candidate won by the smallest margin?

who_won_smallest_margin <- tcp16 %>% 
  filter(Elected == "Y") %>% 
  mutate(percent_margin = 2*(Percent - 50), vote_margin = round(percent_margin * OrdinaryVotes / Percent)) %>% 
  arrange(Percent) %>% 
  mutate(candidate_full_name = paste0(GivenNm, " ", Surname, " (", CandidateID, ")")) %>% 
  select(candidate_full_name, PartyNm, DivisionNm, Percent, OrdinaryVotes, percent_margin, vote_margin)

# have a look
who_won_smallest_margin %>%
 head %>%
 kable

We see that Labor candidate for Herbert, Cathy O'Toole, managed to secure the seat by a margin of only 35 votes - equating to 0.04% of total votes. Let's see the distribution of first preference votes in Herbert for a bit more detail.

herbert_fp <- fp16 %>% 
  filter(DivisionNm == "HERBERT") %>% 
  arrange(-Percent) %>% 
  mutate(candidate_full_name = paste0(GivenNm, " ", Surname, " (", CandidateID, ")")) %>% 
  select(candidate_full_name, PartyNm, DivisionNm, Percent, OrdinaryVotes)

herbert_fp %>% kable

We see that the greatest proportion of first preferences in Herbert actually went to Ewen Jones (Liberal), not to Cathy O'Toole. The win is due to preference flow from minor parties to Labor.

How did each electorate vote in each state?

We can look at the proportion of voters for a particular party in each electorate, grouped by each state. This plot was inspired by Peter Ellis's work on the NZ election data.

# summarise and compute proportion of votes for a particular party
p <- fp16 %>%
  group_by(DivisionNm, StateAb) %>%
  dplyr::summarise(TotalVotes = sum(OrdinaryVotes), 
    ProportionLabor = round(sum(OrdinaryVotes[PartyNm == "AUSTRALIAN LABOR PARTY"]) / TotalVotes, 3)) %>%
  filter(TotalVotes != 0) %>% 
  arrange(desc(ProportionLabor)) %>% 
  group_by(StateAb) %>% 
  # send the data to the plotting function
  do(plots=ggplot(data = .) + 
       aes(x = ProportionLabor, 
           y = reorder(DivisionNm, ProportionLabor), 
           size = TotalVotes, 
           label = StateAb) +
       geom_point() +
       ylab("DivisionNm") +
       labs(title = .$StateAb) + 
       scale_x_continuous("Proportion voting Labor Party", 
                          label = percent) +
       scale_size("Number of\nvotes cast", 
                  label = comma)  +
       theme_bw() +
       theme(text = element_text(size=8)))

# draw the plots
library(gridExtra)
n <- length(p$plots)
nCol <- floor(sqrt(n))
do.call("grid.arrange", c(p$plots, ncol=nCol))

How are party votes correlated?

We can also see how party votes are correlated, for example here we can see a strong negative correlation between votes for Labor and votes for Liberal (this plot also inspired by Peter Ellis). Green and Labor have a slight negative correlation, and Green and Liberal have a slightly more negative correlation:

# Comparing party and candidate votes of several parties -------
proportions <- fp16 %>%
  filter(CandidateID != 999) %>% # exclude informal votes
  group_by(DivisionNm) %>%
  dplyr::summarise(Prop_Labour = sum(OrdinaryVotes[PartyNm == "AUSTRALIAN LABOR PARTY"]) / sum(OrdinaryVotes),
            Prop_Coalition = sum(
              OrdinaryVotes[PartyNm %in% c("LIBERAL PARTY", "NATIONAL PARTY")]
              ) / sum(OrdinaryVotes),
            Prop_Greens = sum(OrdinaryVotes[PartyNm == "THE GREENS"]) / sum(OrdinaryVotes)) 

# make a scatterplot matrix
library(GGally)
ggpairs(proportions, columns = 2:ncol(proportions)) + theme_bw()

How do election results correlate with Census data?

One of our motivations for creating this package was to make it easy to explore relationships between political views and socio-economic conditions across Australia. With a few simple R functions, we can join the Census data to the election data and build models to explore relationships.

Here's how we join the two datasets together, the common variable is the DivisionNm:

census_and_election <- left_join(tpp16, 
                                 abs2016,
                                 by = c("DivisionNm" = "DivisionNm"))

Now we can easily explore some relationships between the Census data and the two party preferred voting patterns. For example, what Census variable mostly strongly correlates with the percentage that vote Labor? The first step in these kinds of explorations is always to visualise the data:

# subset only the columns we want for the model
census_and_election_subset <-  
  census_and_election %>% 
  ungroup %>% 
  select(DivisionNm, 
         ALP_Percent,
         Population:Volunteer_NS) %>% 
  select(-c(ends_with("NS"), EmuneratedElsewhere, InternetUse, starts_with("Age")))


# Plot
library(tibble)
correl_df <- cor(census_and_election_subset[, c(2:ncol(census_and_election_subset))], 
         use = "pairwise.complete.obs") %>% 
  as.data.frame() %>% 
  select(ALP_Percent) %>% 
  rownames_to_column(var = "Covariate") %>% 
  rename("Correlation_with_ALP" = "ALP_Percent") %>% 
  filter(Covariate != "ALP_Percent")

ggplot(aes(x = Correlation_with_ALP, y = reorder(Covariate, Correlation_with_ALP)), data = correl_df) + geom_point()

We can spot some potentially interesting correlations, as well as some obvious ones.

The table below gives an overall summary of the model containing all the Census variables. We see that the p-value is very low, indicating that we have some relationships that are probably not due to chance alone.

options(scipen = 10) # for more readable numbers

# compute the multiple regressions
multiple_regression_model <- 
  census_and_election %>% 
  ungroup %>% 
  select(ALP_Percent,
         Population:Volunteer_NS) %>% 
  select(-c(ends_with("NS"), EmuneratedElsewhere, InternetUse, starts_with("Age"))) %>% 
  lm(ALP_Percent ~ ., 
     data = .)

multiple_regression_model %>% 
  glance %>% 
  dmap(round, 3) %>% 
  kable

The table below shows the variables that have a significant effect on the percentage of Labor votes across all electorates:

# find the variables with a significant effect
multiple_regression_model %>% 
  tidy %>% 
  filter(p.value < 0.05) %>% 
  dmap_if(is.numeric, round, 3) %>% 
  arrange(p.value) %>% 
  kable

In the plots below, we can see the Census variables that have a statistically significant relationship with the percentage of Labor votes. There seems to be a positive relationship between voting Labor and defacto relationships, university education and public housing tenants. Labour force participation and proportion of workers in extractive jobs (e.g. mining, gas, agriculture), and median personal income are a negatively correlated variables, meaning that increases in the proportion of workers in extractive jobs and increases in median personal income correlate with decreases in the percentage of the Labor vote in that electorate.

# model that includes all Census variables
all_vars <- multiple_regression_model %>% 
  tidy %>% 
  filter(p.value < 0.05, term != "(Intercept)") %>% 
  arrange(p.value) 

census_and_election %>% 
  ungroup %>% 
  select_(.dots = all_vars$term,
          "ALP_Percent")  %>% 
  gather(variable, 
         value, 
         -ALP_Percent) %>% 
  ggplot(aes(value, ALP_Percent)) +
  geom_point(size = 0.5) +
  geom_smooth(method = "lm") +
  facet_wrap( ~ variable, scales = "free") +
  theme_bw() + theme(text = element_text(size = 8))


ropenscilabs/eechidna documentation built on May 4, 2023, 6:51 a.m.