How do I qualify a SpatialPolygonsDataFrame using another SpatialPolygonsDataFrame?

78 Views Asked by At

I have Shapefiles from census data from US census.gov.

I've read the files into R using readOGR from the rdgal library.

sp1: voting district - SpatialPolygonsDataFrame

enter image description here

sp2: block level for a larger area and higher resolution than sp1 - SpatialPolygonsDataFrame

enter image description here

I have tried using gIntersection from the rgeos library, but it doesn't return what I need. Or I can't figure out how to use it properly

How do I extract the lower resolution polygons and associated data from sp2 using sp1 as a spacial restriction? In other words, I want to know all the blocks inside sp1 where sp1 and sp2 intersect.

Current Working Solution

The code below returns a vector of index values for sp2 where the polygon had at least one point inside sp1, but I wanted to know if there was an easier way.

library(rgeos)
result <- vector()
for (i in 1:nrow(sp2)) {
    if(gContains(sp1, sp2[i,])) {
        result <- c(result, i)
    }
}
1

There are 1 best solutions below

1
On BEST ANSWER

try

gContains(sp1, sp2, byid = TRUE)

for pair-wise contains relations for feature pairs.

sp2[sp1,]

selects those sp2 features that intersect with sp1, but do read vignette('over') to find out about the limitations (it includes features that only touch).