1

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.

zx8754
  • 52,746
  • 12
  • 114
  • 209
Ankit Sagar
  • 61
  • 1
  • 8
  • Does this answer your question? [Clipping raster using shapefile in R, but keeping the geometry of the shapefile](https://stackoverflow.com/questions/23073669/clipping-raster-using-shapefile-in-r-but-keeping-the-geometry-of-the-shapefile) – Val Mar 03 '21 at 09:39
  • @Val No this solution is to keep the geometry of the vector (i.e WGS84). It doesn't work for me. – Ankit Sagar Mar 03 '21 at 10:22
  • 1
    You need to post a reproducible example (https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with some data so that others can re-create the problem and fix it. – Andrew Chisholm Mar 03 '21 at 10:24

1 Answers1

2

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, ext(v) + .01)
y <- mask(x, v)
plot(y)
lines(v)
Nimantha
  • 6,405
  • 6
  • 28
  • 69
Robert Hijmans
  • 40,301
  • 4
  • 55
  • 63