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

How can I do spatial selections or filters in R? I can do this in PostGIS using (e.g.):

SELECT * FROM mypoint, mypoly
WHERE ST_Within(mypoint.geom, mypoly.geom);

and it is similarly a piece of cake in most other GIS software. So I'd expect something in R to look like:

mypoint[within(mypoint, mypoly),]

but I can't find any leads anywhere. I'm looking for something that uses the common spatial predicate terminology used in PostGIS/GEOS/JTS/Shapely (within, contains, intersects, overlaps, touches, etc.; DWithin would be bonus). Does this functionality or library exist for R? If not, is there something that is similar?

Note: In R, I use the sp class for my objects (SpatialPointsDataFrame, etc).

share|improve this question
up vote 10 down vote accepted

For your specific question, you should be able to use (docs) or overlay (vignette) to perform the analysis.

A spatial predicate language isn't trivial to implement, and all the examples you mentioned boil down to ports or wrappers of JTS at some point. There is a pre-alpha release of rgeos, a recent Google SOC entry which provides access to GEOS directly from R.

In general, it seems that the R developers are grappling with whether they want to maintain a full GIS implementation within R itself, or instead rely on facilitating packages that allow interaction with PostGIS, GRASS (spgrass), SAGA (rsaga) and the like to provide deeper spatial savvy.

share|improve this answer is a good start for basic polygons, although a bit crude (e.g.):[,1], pnt@coords[,2], lake@polygons[[1]]@Polygons[[1]]@coords[,1], lake@polygons[[1]]@Polygons[[1]]@coords[,2]) I'm really looking forward to rgeos that you mentioned, and has all the binary predicates and more. – Mike T Feb 7 '11 at 20:29
For spgrass6 examples with GRASS, see – markusN Feb 8 '11 at 7:25
rgeos is now on CRAN, and is very simple to install/use/etc. – Mike T Oct 11 '11 at 0:20

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.