Last active
February 15, 2017 16:48
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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