Crop for Spatialpolygonsdataframe

Crop for SpatialPolygonsDataFrame

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

Sample Image

how to crop raster based on SpatialPolygons in R

You can use raster::mask. Here's a reproducible example:

library(raster)
r = raster(vals = rnorm(400), nrows=20, ncols=20, ext= extent(c(0, 20, 0, 20)))
p = Polygon(matrix(5, 5, 15, 12, 7, 16, 3, 10), ncol=2, byrow = T))
p = SpatialPolygons(list(Polygons(list(p), "p")))

plot(r)
lines(p)

Sample Image

r2 = mask(r,p)
plot(r2)

Sample Image

If you also need to clip the extent of the raster to remove empty rows and columns around the mask, then you can either use crop before applying mask, or you can use trim(r2, values = NA) afterwards.



Related Topics



Leave a reply



Submit