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.


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,]
  • 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
  • Maybe I'm not reading correctly but this looks slightly wrong? You should extract on a string r of row names, using integers will extract ordinally – MichaelChirico Nov 16 '18 at 3:20
  • @MichaelChirico for returning a known row position this is correct. If you only know the value of the row name(s) than you could create the index using something like which(rownames(x) %in% c(1,5) ) and, no unless a true character string is assigned to rownames than the values do not need to be quoted. The default rownames are a quoted vector of 1:n – Jeffrey Evans Nov 16 '18 at 10:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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