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).


For your specific question, you should be able to use point.in.polygon (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.

  • point.in.polygon is a good start for basic polygons, although a bit crude (e.g.): point.in.polygon(pnt@coords[,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 grass.osgeo.org/wiki/R_statistics – markusN Feb 8 '11 at 7:25
  • 1
    rgeos is now on CRAN, and is very simple to install/use/etc. – Mike T Oct 11 '11 at 0:20

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.