Learn R Programming

prefio (version 0.2.0)

pref_irv: Compute the instant-runoff voting winner for a set of preferences.

Description

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.

Usage

pref_irv(x, preferences_col = NULL, frequency_col = NULL)

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

Arguments

x

A vector of preferences, or a tibble with a column of preferences.

preferences_col

<tidy-select> When x is a tibble, the column containing the preferences.

frequency_col

<tidy-select> When x is a tibble, the column containing the frequency of the preferences. If not provided, each row is considered to be observed a single time.

Examples

Run this code
# 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
result$rounds # Vote tallies for each round

# 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)

Run the code above in your browser using DataLab