Reputation: 91
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.
Upvotes: 4
Views: 5244
Reputation: 47071
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)
Upvotes: 8