2

If I have a set of SpatialPolygons created as such:

library(sp)

Sr2 = Polygon(cbind(c(2,2,1,2,4,4,2),c(2,6,7,7,5,3,2)))
Sr3 = Polygon(cbind(c(4,4,2,5,10,4),c(5,3,2,2,5,5)))
Sr4 = Polygon(cbind(c(5,6,6,5,5),c(4,4,3,3,4)), hole = TRUE)

Srs2 = Polygons(list(Sr2), "s2")
Srs3 = Polygons(list(Sr3, Sr4), "s3/4")
SpP = SpatialPolygons(list(Srs2, Srs3), 1:2)
plot(SpP, col = 2:3, pbg = "white")

Such that it looks like this:

And a vector of points created by:

x <- c(2, 1, 3, 4, 2, 2)
y <- c(2, 4, 2, 2, 3, 4)
points <- cbind(x, y)

How can I detect which points sit inside which polygon, if either?

Thanks

Eugene Brown
  • 4,032
  • 6
  • 33
  • 47
  • OP is trying to find which point is inside which polygon. Would you say this is sufficiently different to the proposed duplicate, @Pascal? – Roman Luštrik Mar 11 '15 at 09:33
  • @Pascal, I'm poking around to see if this is indeed a question worthy of my close vote due to duplication. As I currently see it it's marginal, hence my inquiry. – Roman Luštrik Mar 11 '15 at 10:06
  • @RomanLuštrik Sorry for misunderstanding your comment. Maybe not a duplicate, yes. I should have point this question out, as possible help. –  Mar 11 '15 at 10:15
  • Thank you both for your responses, Pascal my question is indeed a duplicate of that one. I apologise for doubling up and appreciate your pointing me in the right direction and hence answering my question. – Eugene Brown Mar 18 '15 at 02:36

2 Answers2

3

You can use over():

over(SpatialPoints(points), SpP)
# 1  2  3  4  5  6 
# 2 NA  2  2  1  1 

plot(SpP, col = 2:3, pbg = "white", axes=TRUE)
plot(SpatialPoints(points), pch=as.character(1:6), add=TRUE)

plot

rcs
  • 67,191
  • 22
  • 172
  • 153
1

In addition to over you could also use functions from rgeos:

library(rgeos)
pts1 <- gIntersection(SpatialPoints(points), SpP)
plot(SpP, col = 2:3, pbg = "white", axes=TRUE)
points(pts1, pch = 20, col = "blue")

enter image description here

If you want to know the intersection for each point and/or polygon you can use:

gIntersects(SpatialPoints(points), SpP, byid = TRUE)
##        1     2     3     4     5     6
## s2   TRUE FALSE FALSE FALSE  TRUE  TRUE
## s3/4 TRUE FALSE  TRUE  TRUE FALSE FALSE

If the polygon doesn't mapper you could use either:

apply(gIntersects(SpatialPoints(points), SpP, byid = TRUE), 2, any)
##     1     2     3     4     5     6 
##  TRUE FALSE  TRUE  TRUE  TRUE  TRUE 

or

gIntersects(SpatialPoints(points), gUnaryUnion(SpP), byid = TRUE)
##      1     2    3    4    5    6
## 1 TRUE FALSE TRUE TRUE TRUE TRUE
johannes
  • 14,043
  • 5
  • 40
  • 51