I am using R to work with multiband raster files and am running into a problem. I have named the bands, but when I export in netcdf format, the band names are being stripped. Anyone know how to specify band names when exporting netcdf files?
For example, if I have a raster object named "ten", and I type names(ten) I get the vector of band names. If I write ten to disk and then reimport using
newraster = brick("ten.nc"), then the names are stripped away. However, brick() is able to import other .nc files fine with the names attached.
The code I am using is
z = writeRaster(ten,filename = a,overwrite=TRUE,) ### Output to ./outdir folder. This is monthly data
Best Answer
It's because NetCDF does not have names for each slice in the 3rd (and higher dims), but raster does. NetCDF has a name for a "variable" (which is the array), but raster has a name for every slice in the variable. (This is the standard mess where we conflate data fields/attributes with dimensions). There's no straightforward way to store these names in NetCDF without messing around - you'd have to create a dim-var to store them essentially, but there's no clear model of using such a thing in NetCDF.
See how the variable gets the name, but when we round-trip the individual "layers" simply get a layer name, and the varname applies to the whole array. It's the same in GDAL, it unwraps the array to multiple bands (layers) - NetCDF has nowhere for the "dsf1" and "dsf2" to go without extra work at both ends (these would be equivalent to R's dimnames for an array).
And with just one layer, it's clear where the name "dsf" applies - to the entire array:
Without being too critical (since raster is awesome), I think names(raster) is mis-applied, if the raster model was more general it would give only one name no matter whether the grid was 3d, 4d or more, but if you had a different kind of variable - say "temperature" and "pressure" then those would be the names, independent of the dimension of the data. This is a major source of confusion in the murky waters between GIS and the other worlds of modelling.