Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
up vote 7 down vote accepted

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,]
share|improve this answer
I just want to check - will this also work directly on the spdf object? (i.e., spdf[r, ]) – Alberto Apr 13 '13 at 2:48
Yes, it works on sp objects and the index propagates through the ID's that link all of the slot objects, which correspond to the @data rownames. – Jeffrey Evans Apr 13 '13 at 3:19

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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