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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With