Search code examples
rterrancdf4

Set precision of SpatRaster resolution/extent


I need to create a spatRaster to match an existing NetCDF file.

The NetCDF has the following resolution:

gridtype  = lonlat
gridsize  = 8100
xsize     = 90
ysize     = 90
xname     = lon
xlongname = "longitude"
xunits    = "degrees_east"
yname     = lat
ylongname = "latitude"
yunits    = "degrees_north"
xfirst    = -1.04443359375
xinc      = 0.0111083984375
yfirst    = 51.5055541992188
yinc      = 0.0111122131347656

When I read the file in with rast(), the resolution is read in as (N.B. xmin is not the same as xfirst, xfirst is the cell centroid so OK, but the resolution and extents are rounded):

class       : SpatRaster 
dimensions  : 90, 90, 1  (nrow, ncol, nlyr)
resolution  : 0.0111084, 0.01111221  (x, y)
extent      : -1.049988, -0.05023193, 51.5, 52.5001  (xmin, xmax, ymin, ymax)
coord. ref. : lon/lat WGS 84 (CRS84) (OGC:CRS84) 
source      : EMEP4UK_emep-ctm-rv5.0_wrf4.4.2_Defrag_moreLC_trend2021_emiss2021_BD_2021_day_PS.nc 
varname     : PS (PS) 
name        :  PS 
unit        : hPa 
time (days) : 2021-01-01 

Is there a way to force higher precision of resolution/extents.

I've tried terraOptions(datatype = "FLT8S") and creating the SpatRaster manually (for a wider extent to include Europe) e.g.

res_x <- 0.0111083984375
res_y <- 0.0111122131347656

r_ref <- rast(ext(-24.994140625, 35.990966796875, 34.003818511963, 72.9965744018555),
              res = c(res_x,res_y))

> r_ref
class       : SpatRaster 
dimensions  : 3509, 5490, 1  (nrow, ncol, nlyr)
resolution  : 0.0111084, 0.01111221  (x, y)
extent      : -24.99414, 35.99097, 34.00382, 72.99657  (xmin, xmax, ymin, ymax)
coord. ref. : lon/lat WGS 84 

> res(r_ref)
[1] 0.01110840 0.01111221

Solution

  • The digits used to print the summary of your raster need not reflect the true resolution. You could increase the number of digits displayed and check. Example:

    library(terra)
    
    r <- rast(nrows=1, ncols=1, xmin=0, xmax=10, resolution = c(1, 1) + 9e-7)
    

    display with 7 digits shows rounded resolution:

    
        options(digits = 7)
        r
        
        ## class       : SpatRaster 
        ## dimensions  : 180, 10, 1  (nrow, ncol, nlyr)
        ## resolution  : 1.000001, 1.000001  (x, y)
        ## ...
    
    

    display with 8 digits shows true resolution:

    
        options(digits = 8)
        r
    
        ## class       : SpatRaster 
        ## dimensions  : 180, 10, 1  (nrow, ncol, nlyr)
        ## resolution  : 1.0000009, 1.0000009  (x, y)
        ## ...
    
    

    The same holds for other printed information, e. g. res(r).