Skip to content

Instantly share code, notes, and snippets.

@mhweber
Last active February 15, 2017 16:48
Show Gist options
  • Select an option

  • Save mhweber/d87c3fdf9f71ac4f9e69565086ece74f to your computer and use it in GitHub Desktop.

Select an option

Save mhweber/d87c3fdf9f71ac4f9e69565086ece74f to your computer and use it in GitHub Desktop.
Function to find nearest polygons to a set of spatial points and return identifying column from polygons as a column in points attribute table
nearby = function(points, polys, column){
m = gDistance(points, polys, byid=TRUE)
row = apply(m, 2, function(x) which(x==min(x)))
row = sapply(row, "[",1)
labels = unlist(polys@data[row,][[column]])
points$missing <- labels
# head(missing)
return(points@data)
}
library(rgdal); library(rgeos)
points <- readOGR('.','TestPoints')
polys <- readOGR('.','TestPolys')
proj4string(points) == proj4string(polys)
polys = spTransform(polys, CRS(proj4string(points)))
points@data <- nearby(points, polys, 'FieldName')
head(points@data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment