Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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