使用R转换为NetCDF时保留栅格变量名称

时间:2018-05-01 16:24:59

标签: r raster netcdf r-raster ncdf4

获取多年的月度温度数据的光栅文件,其附带的名称可通过names(object)以{Jan.1981','Feb.1981'等格式访问{两年的示例文件代码低于here - 添加所有文件会使其太大。

使用以下代码读取并写入NetCDF:

#Load Packages
library(raster)
library(ncdf4)

#Read in temperature files
r1 <- brick('TavgM_1981.grd')
r2 <- brick('TavgM_1982.grd')

#stack them together 
TempStack = stack(r1, r2)

#set the coordinate system (as it was missing)
crs(TempStack) <- ('+proj=lcc +lat_1=53.5 +lat_2=53.5 +lat_0=46.834 +lon_0=5 +x_0=1488375 +y_0=-203375 +datum=WGS84 +to_meter=2500 +no_defs +ellps=WGS84 +towgs84=0,0,0')

#reproject to get in lat/lon instead of meters
TempStack<-projectRaster(TempStack, crs=CRS("+init=epsg:4326"))

#Extract monthly data names to assign to netCDf later
names <- names(TempStack)

#write the raster file to NetCDF
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=names)

当我把它写入NetCDF并绘制月度数据时,它是从第1个月到第24个月组织的,但我希望它有'1981年1月','1981年2月'等。

我认为通过在writeRaster中添加zunit参数会起作用,但事实并非如此,数字仍然是1-24而不是Jan,Feb等。

1 个答案:

答案 0 :(得分:6)

您的示例中存在一些误解。首先,您应该意识到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)

Haing像这样将日期写入z维度,如果你想将数字z值转换回看起来像&#34; Jan.1908&#34;的栅格图层名称,我们还需要反转这个过程。再次,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)

enter image description here

相关问题