3
votes

I would like to crop a raster based on SpatialPolygons object. I know that we can use crop function in raster package,

raster::crop(rasterFile, SpatialPolygonsObject)

but this function is based on the extent of SpatialPolygons object, so the cropped result is rectangle. However, in some case, SpatialPolygons object is not rectangle, how to deal these situations?

1

1 Answers

4
votes

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)

enter image description here

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

enter image description here

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.