As the title says, I'm struggling with writing the CRS of a multi layer raster stack to a NetCDF file using a custom package. This package uses the functions of the ncdf4-package. But the written .nc file doesn't have the CRS information which the source raster had. I've already read this thread and I tried to replicate it, tweaking the WriteNCDF function from above. I tried it with:
ncatt_put(nc, var.name, 'proj4', crs(data), 'double')
with nc
as the to be written ncdf file and data
as the rasterlayer.
This results in the following error:
Error in ncatt_put_inner(idobj$group_id, idobj$id, attname, attval, prec = prec, : ncatt_put: error, passed an attribute with a storage mode not handled. Att name: proj4 Att value: +proj=utm +zone=32 +datum=WGS84 +units=m +no_defs Storage mode passed: S4 . Handled types: integer double character
Afterwards I tried it with:
ncatt_put(nc, var.name, 'proj4', crs(data, asText = T), 'text')
This doesn't produce an error but when I open the written .nc file with raster::brick()
, the CRS isn't found.
So how do I put CRS information correctly into a NetCDF file?
Minimal code to run:
library('ncdf4')
library('raster')
source('WriteNCDF.R')
r <- raster(crs="+proj=utm +zone=32 +datum=WGS84", xmn=0, xmx=10, ymn=0, ymx=10)
values(r) <- 1:ncell(r)
s <- stack(r, r/2)
x <- writeRaster(s, filename="test.nc")
crs(x)
z <- WriteNCDF(data.l = list(s$layer.1, s$layer.2),
var.name = c('layer1', 'layer2'),
var.unit = c('unit', 'unit'),
file = 'test2.nc',
utm = T)
zz <- brick('test2.nc', varname = 'layer1')
crs(zz)
The tweaked WriteNCDF.R
can be found here.
writeRaster(s, filename="test.nc")
not doing what you want? It saves the data and the CRS. What isWriteNCDF
supposed to do extra?writeRaster()
is on one hand the limitation of meta-data you can write to the .nc files and on the other hand, how to write a multi-layer raster stack where each layer has the same time dimension. If you write a multi-layer raster stack (e.g. all Sentinel-2 bands) withwriteRaster()
ncdf option, every band is another data point on the z-axis (time dimension).