Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clip a raster to the exact outline of a vector (.shp) in R?

I want to clip a Raster Layer exactly to the outline of a shpfile in R.

  crop_rast      = crop (raster , extent(vector))                 # Crop
  mask_rast      = mask (crop_rast, vector)                       # Mask

This doesn't work.

like image 479
Ankit Sagar Avatar asked Oct 28 '25 15:10

Ankit Sagar


1 Answers

One reason why this may not work for you could be that the vector and raster data have a different coordinate reference system.

It does work, with either the raster or the terra package. Here illustrated with terra:

library(terra)
v <- vect(system.file("ex/lux.shp", package="terra"))
r <- rast(system.file("ex/elev.tif", package="terra"))
v <- v[3,]
plot(r)
lines(v, lwd=2)

x <- crop(r, v)
## to add a little bit more space you could do
# x <- crop(r, ext(v) + .01)
y <- mask(x, v)
plot(y)
lines(v)
like image 79
Robert Hijmans Avatar answered Oct 31 '25 06:10

Robert Hijmans



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!