I am trying to extract raster layer names from a netcdf file as previously written from a raster stack. Exporting the raster stack to ncdf works fine. For example:
library(raster)
library(ncdf4)
library(RNetCDF)
#Create some rasters (x3)
r1<-raster(system.file("external/test.grd", package="raster"))
r2<-r1*2
r3<-r2*3
#Stack them
rstack<-stack(r1,r2,r3)
#Give each raster layer a name - in this instance years 2014 to 2016
names(rstack)<-c("2014","2015","2016")
#Write out to netcdf format
writeRaster(rstack, "rstack.nc", overwrite=TRUE, format="CDF", varname="Temperature", varunit="degC",
longname="Temperature -- raster stack to netCDF", xname="X", yname="Y",zname="Year",
zunit="numeric")
However, when I read the ncdf file back into R the Z dimension (i.e. Year) is not retained. E.g:
#Open the new netcdf dataset and look at the Z dimention, i.e. "Year"
data.nc<- open.nc("rstack.nc")
Zdim = var.get.nc(ncfile=data.nc,variable="Year")
print(Zdim)
#[1] 1 2 3
So what we get is the band numbers, i.e. 1,2,3. But what I require is the text defined by Year (e.g. 2014,2015,2016) as defined in:
names(rstack)<-c("2014","2015","2016")
Is it possible to do this?? This problem is not new, refer here: https://gis.stackexchange.com/questions/122167/export-band-names-with-netcdf-file-in-r
There are some convoluted workarounds to get what is required but they seem largely inefficient (i.e. converting the stack to a matrix then manipulating it from here). Just wondering if there is a more elegant way without having to write a large amount of extra code and taking up unnecessary RAM.