Issue with terra::mask

mapsrterra

enter image description hereI try to mask the mapenter image description here in the rectangles with the borders of Switzerland.

 str(swissmask)
S4 class 'SpatVector' [package "terra"]
> swissmask
 class       : SpatVector 
 geometry    : polygons 
 dimensions  : 1, 4  (geometries, attributes)
 extent      : 2485203, 2834035, 1075283, 1295864  (xmin, xmax, ymin, ymax)
 coord. ref. : CH1903+ / LV95 (EPSG:2056) 
 names       :   ID0                       ID1   ID2   ID3
 type        : <chr>                     <chr> <chr> <chr>
 values      :     1 Schweiz/Suisse/Svizzera/~ Area1 Area1

and the map itself

[![> str(x)
S4 class 'SpatRaster' \[package "terra"\]
Warning messages:
1: In class(object) <- "environment" :
  Setting class(x) to "environment" sets attribute to NULL; result will no longer be an S4 object
2: In class(object) <- "environment" :
  Setting class(x) to "environment" sets attribute to NULL; result will no longer be an S4 object

    > x][1]][1]
class       : SpatRaster 
dimensions  : 1141, 1926, 1  (nrow, ncol, nlyr)
resolution  : 200, 200  (x, y)
extent      : 479900, 865100, 73900, 302100  (xmin, xmax, ymin, ymax)
coord. ref. : CH1903 / LV03 (EPSG:21781) 
source(s)   : memory
name        :      V3 
min value   :  193.00 
max value   : 4556.63 

using the code

x <- import("C:/Users/User/Documents/R/Karten/DHM200.csv", setclass = "tibble") %>% 
  mutate(across(everything(), ~ as.double(.))) %>% 
  rast(type = "xyz", crs = cdref) %>% 
  mask(swissmask, inverse = T)

That does not impact the result. What is it I do wrong?

Best Answer

These two objects have different coordinate reference systems, and so very different numerical extents:

extent      : 2485203, 2834035, 1075283, 1295864  (xmin, xmax, ymin, ymax)
coord. ref. : CH1903+ / LV95 (EPSG:2056) 

extent      : 479900, 865100, 73900, 302100  (xmin, xmax, ymin, ymax)
coord. ref. : CH1903 / LV03 (EPSG:21781) 

If you use project to transform your polygons to the coordinate system of the raster then this should work. Hard to confirm without your data, but that's the usual solution.

Note that if I mask with two rasters with different coordinate systems I get a warning message, but I don't get one for masking a raster with a vector. This might be worth reporting.

Related Question