您的示例中存在一些误解。首先,您应该意识到 netcdf 维度中的值必须是数字。它们不仅仅是图层的标签,它们是该维度的实际值,因此不能采用类似的值"Jan.1980"
,这是一个字符串。解决此问题的一种方法是保存 netcdf 文件,然后将 z 维度值作为数值添加到其中。不幸的是,这意味着我们也不能使用日期/时间变量类型,但必须首先将它们转换为等价的数字。这里我使用的是lubridate
包来做到这一点。
# first we write the netcdf file to disk
writeRaster(TempStack, "Temp.nc", overwrite=TRUE,
format="CDF", varname="Temperature", varunit="degC",
longname="Temperature -- raster stack to netCDF, monthly average",
xname="Longitude", yname="Latitude", zname='Time', zunit='seconds')
# and open a connection to it to make changes.
# note that we use write=TRUE so that we can change it
nc = nc_open('Temp.nc', write = TRUE)
# now convert the strings to numeric values based on their dates
zvals = lubridate::parse_date_time(names, orders = 'm.y', tz = "UTC")
zvals = as.integer(zvals)
# and we can write these numeric dates to the z dimension
ncdf4::ncvar_put(nc, 'Time', zvals)
像这样将日期写入 z 维度后,如果您想将数字 z 值转换回类似于“Jan.1908”等的栅格图层名称,我们还需要反转该过程。同样,lubridate 可以提供帮助。
ncb = brick('Temp.nc')
zvals = ncvar_get(nc, 'Time')
zvals = as.POSIXct(zvals, origin = lubridate::origin, tz = "UTC")
znames = paste0(lubridate::month(zvals, label=T), '.', lubridate::year(zvals))
names(ncb) = znames
让我们检查一下是否有效:
plot(ncb)