nearest_location: Find nearest polling locations for each voter

View source: R/nearest_location.R

nearest_locationR Documentation

Find nearest polling locations for each voter

Description

Calculates the distance between each voter and a set of polling/drop box locations using the Haversine formula. Can return the single nearest location, the k nearest, or all locations within a distance threshold.

Usage

nearest_location(
  voters,
  locations,
  voter_coords = NULL,
  location_coords = NULL,
  k = 1L,
  max_dist = NULL,
  units = c("km", "miles", "meters"),
  append_data = TRUE,
  progress = FALSE
)

Arguments

voters

A data frame, matrix, or sf POINT object containing voter locations. If a data frame or matrix, must contain lat/lon columns specified by voter_coords.

locations

A data frame, matrix, or sf POINT object containing polling/drop box locations. If a data frame or matrix, must contain lat/lon columns specified by location_coords.

voter_coords

Character vector of length 2: c("lat_col", "lon_col") identifying the latitude and longitude columns in voters. Ignored if voters is an sf object.

location_coords

Character vector of length 2: c("lat_col", "lon_col") identifying the latitude and longitude columns in locations. Ignored if locations is an sf object.

k

Integer. Number of nearest locations to return per voter. Default 1.

max_dist

Numeric or NULL. If not NULL, return all locations within this distance of each voter. Units controlled by units. Overrides k.

units

Character. One of "km", "miles", or "meters". Default "km".

append_data

Logical. If TRUE (default), include voter and matched location columns in the output. When k = 1, also appends the matched location row.

progress

Logical. If TRUE, print progress for large computations. Default FALSE.

Value

A data frame. If k = 1 and max_dist is NULL: one row per voter with distance columns (distance_m, distance_km, distance_miles). If k > 1 or max_dist is not NULL: one row per voter-location pair with a rank column.

Examples

data(meck_ev)

# Nearest single location for each voter
result <- nearest_location(voter_meck, early_meck,
  voter_coords = c("lat", "long"),
  location_coords = c("lat", "long"))
head(result)

# 3 nearest locations per voter
result_k3 <- nearest_location(voter_meck, early_meck,
  voter_coords = c("lat", "long"),
  location_coords = c("lat", "long"),
  k = 3)
head(result_k3)

# All locations within 10 km
result_10km <- nearest_location(voter_meck, early_meck,
  voter_coords = c("lat", "long"),
  location_coords = c("lat", "long"),
  max_dist = 10, units = "km")
head(result_10km)

Rvoterdistance documentation built on May 28, 2026, 1:06 a.m.