Also asked here
Using R, I would like to overlay some spatial points and polygons in order to assign to the points some attributes of the geographic regions I have taken into consideration.
What I usually do is to use the command
over of the
sppackage. My problems is that I'm working with a large number of geo-referenced events that happened all over the globe and in some cases (especially in coastal areas), the longitude and latitude combination falls slightly outside the country/region border.
Here a reproducible example based on in this very good question.
## example data set.seed(1) library(raster) library(rgdal) library(sp) p <- shapefile(system.file("external/lux.shp", package="raster")) p2 <- as(0.30*extent(p), "SpatialPolygons") proj4string(p2) <- proj4string(p) pts1 <- spsample(p2-p, n=3, type="random") pts2<- spsample(p, n=10, type="random") pts<-rbind(pts1, pts2) ## Plot to visualize plot(pts, pch=16, cex=.5,col="red") plot(p, col=colorRampPalette(blues9)(12), add=TRUE)
# overlay pts_index<-over(pts, p) # result pts_index ID_1 NAME_1 ID_2 NAME_2 AREA 1 NA <NA> <NA> <NA> NA 2 NA <NA> <NA> <NA> NA 3 NA <NA> <NA> <NA> NA 4 1 Diekirch 2 Diekirch 218 5 3 Luxembourg 8 Capellen 185 6 3 Luxembourg 9 Esch-sur-Alzette 251 7 3 Luxembourg 8 Capellen 185 8 1 Diekirch 1 Clervaux 312 9 1 Diekirch 2 Diekirch 218 10 3 Luxembourg 8 Capellen 185 11 1 Diekirch 2 Diekirch 218 12 1 Diekirch 3 Redange 259 13 2 Grevenmacher 7 Remich 129
Is there a way to give to the
over function a sort of tolerance in order to capture also the points that are very close to the border?
Following this I could assign to the missing point the nearest polygon, but this is not exactly what I am after.