library(sf) library(FNN) library(dplyr) setwd("") # --- Inputs (files should be in your working directory) --- footprints <- st_read("Footprints_county_sample.shp", quiet = TRUE) schools <- st_read("EDGE_GEOCODE_PUBLICSCH_2122.shp", quiet = TRUE) # Align CRS: transform schools to footprints' CRS schools <- st_transform(schools, st_crs(footprints)) # If the CRS is geographic (degrees), reproject both to a projected CRS (meters) for correct distances # Here we use EPSG:5070 (NAD83 / Conus Albers) which is good for CONUS-wide work. if (sf::st_is_longlat(footprints)) { target_crs <- 5070 footprints <- st_transform(footprints, target_crs) schools <- st_transform(schools, target_crs) } # Ensure an 'index' exists if (!"index" %in% names(footprints)) { footprints$index <- seq_len(nrow(footprints)) } # Centroid coordinates (matrix of x,y) foot_xy <- st_coordinates(st_centroid(footprints)) school_xy <- st_coordinates(st_centroid(schools)) # 1-NN: for each footprint, distance to the nearest school (same units as CRS; meters if projected) nn <- FNN::get.knnx(data = school_xy, query = foot_xy, k = 1) # Assemble output table: index + distance Foot_school_distances <- tibble::tibble( index = footprints$index, Foot_school_distances = as.numeric(nn$nn.dist) ) # Save result save(Foot_school_distances, file = "Foot_school_distances.RData")