## ----setup, include = FALSE---------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)

## ----install, eval = FALSE----------------------------------------------------
# # From GitHub:
# remotes::install_github("lorenc5/Rvoterdistance")

## ----data---------------------------------------------------------------------
library(Rvoterdistance)
data(meck_ev)

str(voter_meck)
str(early_meck)

## ----nearest------------------------------------------------------------------
result <- nearest_location(
  voters    = voter_meck,
  locations = early_meck,
  voter_coords    = c("lat", "long"),
  location_coords = c("lat", "long")
)

head(result)

## ----knearest-----------------------------------------------------------------
result_k3 <- nearest_location(
  voter_meck, early_meck,
  voter_coords    = c("lat", "long"),
  location_coords = c("lat", "long"),
  k = 3,
  append_data = FALSE
)

head(result_k3, 9)

## ----threshold----------------------------------------------------------------
result_5mi <- nearest_location(
  voter_meck[1:20, ], early_meck,
  voter_coords    = c("lat", "long"),
  location_coords = c("lat", "long"),
  max_dist = 5,
  units = "miles",
  append_data = FALSE
)

head(result_5mi, 10)

# How many locations within 5 miles per voter?
table(result_5mi$voter_id)

## ----sf, eval = requireNamespace("sf", quietly = TRUE)------------------------
library(sf)

voters_sf <- st_as_sf(voter_meck, coords = c("long", "lat"), crs = 4326)
locs_sf   <- st_as_sf(early_meck, coords = c("long", "lat"), crs = 4326)

result_sf <- nearest_location(voters_sf, locs_sf, append_data = FALSE)
head(result_sf)

## ----convenience--------------------------------------------------------------
# Minimum distance in km for each voter
km <- dist_km(voter_meck$lat, voter_meck$long,
              early_meck$lat, early_meck$long)
summary(km)

# Minimum distance in miles
mi <- dist_mile(voter_meck$lat, voter_meck$long,
                early_meck$lat, early_meck$long)
summary(mi)

# Single-pair distance (e.g., Charlotte to Raleigh)
haversine(35.2271, -80.8431, 35.7796, -78.6382, units = "miles")

## ----progress, eval = FALSE---------------------------------------------------
# result <- nearest_location(
#   big_voter_file, locations,
#   voter_coords = c("lat", "lon"),
#   location_coords = c("lat", "lon"),
#   k = 3,
#   progress = TRUE
# )

