Skip to content
Prev 20565 / 29559 Next

overlapping polygons in shapefile

Initial example below, please scroll down:
On Wed, 12 Mar 2014, Roger Bivand wrote:

            
A first cut at an example:

library(sp)
library(rgeos)
box <- readWKT("POLYGON((0 0, 0 1000, 1000 1000, 1000 0, 0 0))")
plot(box)
set.seed(1)
pts <- spsample(box, n=2000, type="random")
pols <- gBuffer(pts, byid=TRUE, width=50)
plot(pols, add=TRUE)
STR <- gBinarySTRtreeQuery(pols, pols)
length(STR)
summary(sapply(STR, length))
res <- vector(mode="list", length=length(STR))
for(i in seq(along=STR)) res[[i]] <- gOverlaps(pols[i], pols[STR[[i]]],
   byid=TRUE)
summary(sapply(res, sum)-1) # to remove self-counting, i overlaps i

So then we have # overlap counts per input polygon - but what are the 
output reporting units? Should we actually be counting the number of 
polygons that a fine grid of points over box belong to? If we focus on 
this, then maybe:

GT <- GridTopology(c(0.5, 0.5), c(1, 1), c(1000, 1000))
SG <- SpatialGrid(GT)
o <- over(SG, pols, returnList=TRUE)
ct <- sapply(o, length)
summary(ct)
SGDF <- SpatialGridDataFrame(SG, data=data.frame(ct=ct))
spplot(SGDF, "ct", col.regions=bpy.colors(20))

is closer? I haven't checked why the overlaps and the grid over counts 
differ - homework for someone? How does the output resolution affect the 
detected number of hits?

Roger