Ankit Sagar
Ankit Sagar

Reputation: 91

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.

Upvotes: 4

Views: 5244

Answers (1)

Robert Hijmans
Robert Hijmans

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

Related Questions