Skip to content

Instantly share code, notes, and snippets.

@h-a-graham
Created June 28, 2022 16:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save h-a-graham/b991c5b60375fa2e70f198ef49276cae to your computer and use it in GitHub Desktop.
Save h-a-graham/b991c5b60375fa2e70f198ef49276cae to your computer and use it in GitHub Desktop.
get nearest points and set geometry as the point closest to the original measurement
library(sf)
library(dplyr)
library(mapview)
mapviewOptions(fgb = FALSE)
plts <- read_sf('data/PlotData/KuamutLocations.shp')
pnts <- read_sf("data/Kuamut_2022_NewGPS_Points_Shapefiles/PlotCentre.shp")
pnts_clean <- pnts %>%
filter(is.na(NUMBER)|NUMBER!=100) %>%
mutate(nearest = st_nearest_feature(., plts),
plot_join = plts$Pl[nearest], # not really needed but just in case the row numbers and plot numbers don't match
NUMBER = as.integer(NUMBER),
NUMBER = case_when(is.na(NUMBER) ~ plot_join,
TRUE~NUMBER),
dist = st_distance(., plts[nearest,], by_element=TRUE)) %>%
group_by(NUMBER) %>%
mutate(geometry = geometry[which.min(dist)])
mapview(plts, col.regions='red') +
mapview(pnts, col.regions='blue') +
mapview(pnts_clean, col.regions='green')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment