Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to crop raster based on SpatialPolygons in R

Tags:

r

crop

sp

r-raster

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?

like image 571
just_rookie Avatar asked Mar 11 '23 05:03

just_rookie


1 Answers

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.

like image 108
dww Avatar answered Mar 15 '23 13:03

dww