[GIS] Subset a SpatialPolygonsDataFrame by ID in R

r

I've used the gIntersect function from the rgeos package to determine which polygons intersect in two SpatialPolygonsDataFrames (spdfs). The result is a logical matrix with rownames comprising the polygon IDs from sfdf #1 and colnames the polygon IDs from spdf #2. I'd like to use this matrix to subset the two original spdfs, omitting those polygons that have no overlap, before using the function gIntersection. I can easily convert the logical matrix into two vectors of IDs (one for each spdf) that represent those polygons with at least some overlap.

My question is – can I use a vector of polygon IDs to subset a spdf? If so, will it correctly subset values in the @data slot? I know I can generally subset spdfs using this syntax:

spdf[spdf@data$myVariable[someVector], ]

This won't work for IDs, as they are buried much deeper inside the spdf list structure.

Best Answer

The matrix ids returned from gIntersect should correspond to the rownames in each source sp object. You should be able to just index the rownames position in order to subset the data.

r <- c(1,5,3,9,10)
sp.polys <- sp.polys[r,]