Skip to content

[get_sim2_daily]: impossible to write netCDF for CRS different than Lambert 2

Check this:

bbox_L93 <- sf::st_bbox(
  c(
    xmin = 760000,
    xmax = 783000,
    ymin = 6270000,
    ymax = 6290000
  ),
  crs = sf::st_crs(2154) # RGF93 / Lambert-93
)
mask <- sf::st_as_sf(sf::st_as_sfc(bbox_L93))

clim <- get_sim2_daily(mask, DATE__greater = Sys.Date() - 30, fields = "T_Q", overlay_mode = "extent")

clim 
stars object with 3 dimensions and 1 attribute
attribute(s):
         Min. 1st Qu. Median     Mean 3rd Qu. Max.
T_Q [°C] 20.4    23.5   24.5 24.74957    25.5   29
dimension(s):
     from to                refsys                    values x/y
x       1  4 RGF93 v1 / Lambert-93   [4x4] 762191,...,786367 [x]
y       1  4 RGF93 v1 / Lambert-93 [4x4] 6265709,...,6289885 [y]
time    1 29                  Date 2025-08-01,...,2025-07-31    
curvilinear grid

file_nc <- tempfile(fileext = ".nc")
stars::write_mdim(clim, file_nc)
Warning messages:
1: In CPL_write_mdim(file, driver, dimx, cdl, wkt, xy, root_group_options,  :
  GDAL Message 1: Dimension y lacks a indexing variable
2: In CPL_write_mdim(file, driver, dimx, cdl, wkt, xy, root_group_options,  :
  GDAL Message 1: Dimension x lacks a indexing variable
3: In CPL_write_mdim(file, driver, dimx, cdl, wkt, xy, root_group_options,  :
  GDAL Error 1: netcdf error #-59 : NetCDF: Name contains illegal characters .
at (../../../gdal-3.11.0/frmts/netcdf/netcdfmultidim.cpp,IWrite,4805)
4: In CPL_write_mdim(file, driver, dimx, cdl, wkt, xy, root_group_options,  :
  GDAL Error 6: SetIndexingVariable() not implemented

clim_read <- stars::read_mdim(file_nc)
clim_read
stars object with 3 dimensions and 1 attribute
attribute(s):
         Min. 1st Qu. Median     Mean 3rd Qu. Max.
T_Q [°C] 20.4    23.5   24.5 24.74957    25.5   29
dimension(s):
     from to offset delta                refsys                    values x/y
x       1  4    0.5     1 RGF93 v1 / Lambert-93                      NULL [x]
y       1  4    0.5     1 RGF93 v1 / Lambert-93                      NULL [y]
time    1 29     NA    NA                  Date 2025-08-01,...,2025-07-31    

Coordinates are not kept during NetCDF saving with write_mdim. The reason is that this function does not handle raster grid with curvilinear coordinates.

write_stars handles this case but is not able to save more than one attribute (variable).

It doesn't seem it exists a technical solution on R to handle this case easily. The simplest solution is to save the stars object in RDS format.