rspatialterra

Cropping a raster using terra does not return the expected extent


I have a raster whose extent is -180.049996946546, 179.949996948242, -90.05, 90.05 (xmin, xmax, ymin, ymax). I need it to allign it with other rasters that have the same CRS but an extent of -180, 180, -90, 90 (xmin, xmax, ymin, ymax). I am trying to cut it using the crop function of the terra package but for some reasons this does not return the exact extent I want, namely -180, 180, -90, 90 (xmin, xmax, ymin, ymax).

Can anyone advice?

myraster |> ext()
SpatExtent : -180.049996946546, 179.949996948242, -90.05, 90.05 (xmin, xmax, ymin, ymax)
new_extent
SpatExtent : -180, 180, -90, 90 (xmin, xmax, ymin, ymax)
myraster_cropped=crop(myraster,new_extent ,extend=TRUE)
myraster_cropped |> ext()
SpatExtent : -180.049996946546, 180.049996946546, -89.95, 90.05 (xmin, xmax, ymin, ymax)

Details of myraster

> myraster
class       : SpatRaster 
dimensions  : 1801, 3600, 1  (nrow, ncol, nlyr)
resolution  : 0.1, 0.1  (x, y)
extent      : -180.05, 179.95, -90.05, 90.05  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +datum=WGS84 +no_defs 
source(s)   : memory
varname     : t2m (2 metre temperature) 
name        :    t2m_1 
min value   : 229.8191 
max value   : 306.1671 
unit        :        K 
time        : 2000-01-01 UTC

Solution

  • Your data

    libary (terra)
    r <- rast(xmin=-180.05, xmax=179.95, ymin=-90.05, ymax=90.05, res=.1)
    

    This is, of course, a very odd extent. Especially having latitudes >90 and < -90 makes no sense. Unfortunately, climate model data if often provided that way.

    If you do

    newext <- ext(-180, 180, -90, 90)
    crop(r, newext) |> ext()
    #SpatExtent : -180.05, 179.95, -89.95, 89.95 (xmin, xmax, ymin, ymax)
    

    The extent does not change the way you would like because crop can only remove entire rows and columns. You can use terra::resample

    x <- rast(res=0.1)
    x <- resample(r, x)
    

    And, yes this will change the values (depending on the value for argument "method") but that is desirable in this case since the extent shifts half a cell, there is no good way around that.