1. Read & clean AEC CSV files

2. Victoria – first preferences by party

3. Victoria – marginal divisions (TCP)

---
title: "S4123208_Assignment_3"
output:
  flexdashboard::flex_dashboard:
    storyboard: true
    theme: flatly
    source_code: embed
---


```{r setup, include=FALSE}
library(tidyverse)
library(flexdashboard)
library(readr)
library(stringr)
library(tidyverse)
library(janitor)
knitr::opts_chunk$set(message = FALSE, warning = FALSE)
```

### 1. Read & clean AEC CSV files

```{r}
tcp <- readr::read_csv("HouseTcpByCandidateByPollingPlaceDownload-31496.csv",
                       skip = 1) |>
  clean_names()
prefs_vic <- readr::read_csv("HouseStateFirstPrefsByPollingPlaceDownload-31496-VIC.csv",
                             skip = 1) |>
  clean_names()
```

### 2. Victoria – first preferences by party
```{r}
# total first-preference votes by party (VIC)
vic_summary_party <- prefs_vic |>
  group_by(party_nm) |>
  summarise(total_votes = sum(ordinary_votes, na.rm = TRUE), .groups = "drop") |>
  mutate(share = 100 * total_votes / sum(total_votes)) |>
  arrange(desc(share))

ggplot(vic_summary_party, aes(x = reorder(party_nm, share), y = share)) +
  geom_col() +
  coord_flip() +
  labs(
    title = "Victoria – first preference vote share by party",
    x = NULL,
    y = "Vote share (%)"
  ) +
  theme_minimal(base_size = 13)
```

### 3. Victoria – marginal divisions (TCP) <!-- third slide -->
```{r}
tcp_division_totals <- tcp |>
group_by(division_nm, party_nm) |>
summarise(total_votes = sum(ordinary_votes, na.rm = TRUE), .groups = "drop")




marginals_vic <- tcp_division_totals |>
group_by(division_nm) |>
mutate(share = 100 * total_votes / sum(total_votes)) |>
arrange(division_nm, desc(share)) |>
summarise(margin = diff(share), .groups = "drop") |>
slice_min(margin, n = 10)




ggplot(marginals_vic, aes(x = reorder(division_nm, margin), y = margin)) +
geom_col() +
coord_flip() +
labs(title = "Most marginal divisions in Victoria (2025)",
x = NULL, y = "Margin (percentage points)") +
theme_minimal()
```