Skip to content

Instantly share code, notes, and snippets.

@aghaynes
Created May 22, 2018 12:59
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 aghaynes/d3131233506e9ef1623222232d6d5502 to your computer and use it in GitHub Desktop.
Save aghaynes/d3131233506e9ef1623222232d6d5502 to your computer and use it in GitHub Desktop.
Toy example of a one to many intersection between points and polygons
library(sp)
# create polygons
p1 <- matrix(c(1,1,
2,1,
4,2,
3,2), ncol = 2, byrow = TRUE)
p2 <- matrix(c(2.2,1,
3,1,
3,2,
3,3,
2.8,3), ncol = 2, byrow = TRUE)
p1s <- Polygons(list(Polygon(p1)), 3)
p2s <- Polygons(list(Polygon(p2)), 4)
sps <- SpatialPolygons(list(p1s, p2s))
#create points
point <- matrix(c(2.5, 1.5,
3.2, 1.75,
2,3,
1.5, 1.25,
2.75, 2.5), ncol = 2, byrow = TRUE)
points <- SpatialPoints(point)
plot(sps, border = c("black", "blue"))
plot(points, add = TRUE)
#returns only a single hit per point
over(points, sps)
#create list of SpatialPolygons from original SpatialPolygons
sps2 <- lapply(sps@polygons, function(x) SpatialPolygons(list(x)))
#returns a list for each polygon, saying which points are enclosed
lapply(sps2, function(x) over(points, x))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment