0

I have two spatial objects, one polygon and one points. The polygons may overlap. I would like to associate each point with ALL the polygons it falls in. When the polygons do not overlap, I can do a simple points in polygons, but I am a bit stuck in the case of overlapping polygons. For example:

square<-rbind(c(10,10,20,20,15,25,25,15),
              c(15,15,25,25,10,20,20,10))

ID<-c("A","B")

polys<-SpatialPolygons(list(
  Polygons(list(Polygon(matrix(square[1, ], ncol=2, byrow=FALSE))), ID[1]),
  Polygons(list(Polygon(matrix(square[2, ], ncol=2, byrow=FALSE))), ID[2])
))

x<-c(15,17,22,22)
y<-c(22,18,12,22)
data<-data.frame(ID=c(1,2,3,4))
# points from scratch
coords = cbind(x, y)
sp = SpatialPoints(coords)
# make spatial data frame
points = SpatialPointsDataFrame(coords, data)
points = SpatialPointsDataFrame(sp, data)

Point 1 is inside Polygon A; Point 2 is inside Polygon A and B; Point 3 is inside Polygon B; Point 4 is inside NO Polygon.

Ideally I would like a data frame like this:

ID P1 P2 P3 ...
1  A  NA NA
2  A  B  NA
3  B  NA NA
4  NA NA NA

A priory I can't judge how many potential overlapping polygons that each point falls in but I can set a large upper limit and hope that it is sufficient.

0

Use raster::extract() function:

library(raster)

e <- extract(polys,points)

names(e) <- c('point','poly')

e
##   point poly
## 1     1    1
## 2     2    1
## 3     2    2
## 4     3    2
## 5     4   NA

And you can spread rows with table():

as.matrix(table(e))
##      poly
## point 1 2
##     1 1 0
##     2 1 1
##     3 0 1
##     4 0 0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.