Compute the instant-runoff voting winner for a set of preferences.
Source:R/pref_summaries.R
pref_irv.Rd
A very rudimentary implementation of the IRV counting algorithm. It does not handle ties elegantly, and should only be used for demonstration purposes. This implementation eliminates all candidates with the fewest first-choice votes in each round until one candidate has a majority or fewer than two candidates remain.
Arguments
- x
A vector of preferences, or a tibble with a column of preferences.
- preferences_col
<
tidy-select
> Whenx
is atibble
, the column containing the preferences.- frequency_col
<
tidy-select
> Whenx
is atibble
, the column containing the frequency of the preferences. If not provided, each row is considered to be observed a single time.
Value
A list containing:
- winner
The winning candidate(s) after IRV counting
- rounds
A list of tibbles, each containing vote tallies for each round
- eliminated
Character vector of eliminated candidates in order
Examples
# Multi-round election with four candidates
prefs <- preferences(c(
"alice > bob > charlie > david",
"alice > bob > charlie > david",
"alice > charlie > bob > david",
"bob > alice > charlie > david",
"bob > charlie > alice > david",
"bob > charlie > alice > david",
"charlie > david > alice > bob",
"charlie > david > bob > alice",
"david > charlie > bob > alice",
"david > charlie > bob > alice"
))
result <- pref_irv(prefs)
result$winner # Final winner after elimination rounds
#> [1] "bob"
result$rounds # Vote tallies for each round
#> [[1]]
#> # A tibble: 4 × 2
#> candidate value
#> <chr> <int>
#> 1 alice 3
#> 2 bob 3
#> 3 charlie 2
#> 4 david 2
#>
#> [[2]]
#> # A tibble: 2 × 2
#> candidate value
#> <chr> <int>
#> 1 alice 4
#> 2 bob 6
#>
# Using aggregated data frame
df <- tibble::tibble(
prefs = preferences(c(
"alice > bob > charlie > david",
"alice > charlie > bob > david",
"bob > alice > charlie > david",
"bob > charlie > alice > david",
"charlie > david > alice > bob",
"charlie > david > bob > alice",
"david > charlie > bob > alice"
)),
freq = c(2, 1, 1, 2, 1, 1, 2)
)
pref_irv(df, prefs, freq)
#> $winner
#> [1] "bob"
#>
#> $rounds
#> $rounds[[1]]
#> # A tibble: 4 × 2
#> candidate value
#> <chr> <int>
#> 1 alice 3
#> 2 bob 3
#> 3 charlie 2
#> 4 david 2
#>
#> $rounds[[2]]
#> # A tibble: 2 × 2
#> candidate value
#> <chr> <int>
#> 1 alice 4
#> 2 bob 6
#>
#>
#> $eliminated
#> [1] "alice" "charlie" "david"
#>