Given a Spatial object in R, how do I clip all of its elements to lie within a bounding box?
There are two things I'd like to do (ideally I'd know how to do both, but either is an acceptable solution to my current problem–restricting a polygon shapefile to the continental U.S.).
-
Drop each element not fully within the bounding box. This seems like
bbox()<-
would be the logical way, but no such method exists. -
Do a true clip operation, such that non-infinitesimal elements (e.g. polygons, lines) are cut off at the boundary.
sp::bbox
lacks an assignment method, so the only way I've come up with would be to useover
orgContains
/gCrosses
in conjunction with a SpatialPolygons object containing a box with the new bounding box's coordinates. Then when clipping a polygon object, you'd have to figure out which are contained vs. cross, and alter the coordinates of those polygons so that they don't exceed the box. Or something likegIntersection
. But surely there's a simpler way?
While I know that there are many problems with bounding boxes, and that a spatial overlay to a polygon that defines the region of interest is typically preferable, in many situations, bounding boxes work fine and are simpler.
Best Answer
I've created a small function for this very purpose and it has been used by others with good reviews!
This should solve your problem. Further explanation is here: http://robinlovelace.net/r/2014/07/29/clipping-with-r.html
The dummy polygon
b_poly
that is created has no proj4 string, which results in "Warning: spgeom1 and spgeom2 have different proj4 strings", but this is harmless.