Streamlined method added 2014-10-9:
raster::crop()
can be used to crop Spatial*
(as well as Raster*
) objects.
For example, here's how you might use it to crop a SpatialPolygons*
object:
## Load raster package and an example SpatialPolygonsDataFrame
library(raster)
data("wrld_simpl", package="maptools")
## Crop to the desired extent, then plot
out <- crop(wrld_simpl, extent(130, 180, 40, 70))
plot(out, col="khaki", bg="azure2")
Original (and still functional) answer:
The rgeos function gIntersection()
makes this pretty straightforward.
Using mnel's nifty example as a jumping off point:
library(maptools)
library(raster) ## To convert an "Extent" object to a "SpatialPolygons" object.
library(rgeos)
data(wrld_simpl)
## Create the clipping polygon
CP <- as(extent(130, 180, 40, 70), "SpatialPolygons")
proj4string(CP) <- CRS(proj4string(wrld_simpl))
## Clip the map
out <- gIntersection(wrld_simpl, CP, byid=TRUE)
## Plot the output
plot(out, col="khaki", bg="azure2")
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…