I have a SpatialPointsDataFrame
and a SpatialPolygons
. I want to check for each point in SpatialPointsDataFrame
, which polygon in the SpatialPolygons
does it lie.
I can do this using sp::over
to achieve this:
However for cases where some of the points in SpatialPointsDataFrame
lie either on the edges
or outside the polygon and in such cases I want to assign the nearest polygon from the
SpatialPolygons
. Here's the sample dataset:
set.seed(1)
library(raster)
library(rgdal)
library(rgeos)
p <- shapefile(system.file("external/lux.shp", package="raster"))
p2 <- as(1.5*extent(p), "SpatialPolygons")
proj4string(p2) <- proj4string(p)
pts <- spsample(p2, n=10, type="random")
## Plot to visualize
plot(p, col=colorRampPalette(blues9)(12))
plot(pts, pch=16, cex=.5,col="red", add = TRUE)
over(pts, p)
ID_1 NAME_1 ID_2 NAME_2 AREA
1 1 Diekirch 3 Redange 259
2 NA <NA> NA <NA> NA
3 NA <NA> NA <NA> NA
4 NA <NA> NA <NA> NA
5 NA <NA> NA <NA> NA
6 NA <NA> NA <NA> NA
7 3 Luxembourg 10 Luxembourg 237
8 3 Luxembourg 8 Capellen 185
9 2 Grevenmacher 6 Echternach 188
10 NA <NA> NA <NA> NA
All rows with NA are the ones I need to assign the nearest polygon.