how to crop raster based on SpatialPolygons in R
Asked Answered
C

1

6

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?

Clod answered 8/1, 2017 at 5:16 Comment(0)
B
9

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.

Belief answered 8/1, 2017 at 6:4 Comment(3)
Thank you for your reply. But how to remove these cells that not included in the mask?Clod
But you can do crop before mask to eliminate as many cells as possibleNewbold
or you use the trim function (from the raster package) to remove outer rows and columns with NA values: trim(r2, values = NA)Baler

© 2022 - 2024 — McMap. All rights reserved.