Skip to content

Counting overlapping polygons in a given area

3 messages · Andrew Bernj, Roger Bivand

#
On Thu, 17 Apr 2014, Andrew Bernj wrote:

            
On lists in this community, it is usual to follow the instructions, in 
particular to provide a toy example illustrating your problem. If you 
don't, nobody knows whether the suggested resolution matches your problem. 
You also posted HTML-mail; please use plain text only, so that included 
code may be pasted straight into an R console.
library(sp)
library(rgdal)
dsn <- system.file("vectors", package = "rgdal")[1]
scot_BNG <- readOGR(dsn=dsn, layer="scot_BNG")
plot(scot_BNG, axes=TRUE)

gives something like UScities.shp.

set.seed(1)
pts <- spsample(scot_BNG, n=200, type="random")
plot(pts, add=TRUE, col="red")
library(rgeos)
polys <- gBuffer(pts, width=50000, byid=TRUE)
plot(polys, add=TRUE, border="red")

gives something like USrelig.shp.

library(rgeos)
gO <- gOverlaps(scot_BNG, polys, byid=c(TRUE, TRUE))
dim(gO)

makes a logical matrix with TRUE where scot_BNG[i,] overlaps with 
polys[j].

count_by_city <- apply(gO, 2, sum)

The output vector is named using row.names(scot_BNG), so if you need 
recognizable names in the output, change the input row.names to something 
informative.

This is OK if the number of cities times the number of religions is 
moderate. If the product is large, try the development version of rgeos 
from:

https://r-forge.r-project.org/R/?group_id=602

and use:

gO <- gOverlaps(scot_BNG, polys, byid=c(TRUE, TRUE), returnDense=FALSE)
length(gO)
count_by_city1 <- sapply(gO, length)

and in this case we see that they are equivalent:

all.equal(count_by_city, count_by_city1)

Hope this helps,

Roger

  
    
3 days later
#
Dear Roger,

Thank you very much for this example. It was exactly what I needed to
get started on this issue. Especially the final part, using the
development version of rgeos. I have been trying some different things
before and I suspect one of the problems had to do with the fact that
I have just too many cities*religions. It helped a lot with other
problems I had to solve.

Also, I do apologize for not sending my previous code or a toy
exmaple. I will remember that in the future.

Best,

Andrew



2014-04-17 5:19 GMT-04:00 Roger Bivand <Roger.Bivand at nhh.no>: