Writing R raster stack to NetCDF

2019-06-12 09:54发布

问题:

I've got an R grid file containing monthly temperature data for the year 1981 which I read in and tried to write to NetCDF using the following code:

library(raster)
library(ncdf4)
library(RNetCDF)

test <- raster('.../TavgM_1981.gri', package = "raster")
rstack = stack(test)

writeRaster(rstack, "rstack.nc", overwrite=TRUE, format="CDF",     varname="Temperature", varunit="degC", 
        longname="Temperature -- raster stack to netCDF", xname="X",   yname="Y",zname="nbands",
        zunit="numeric")

This writes the NetCDF file, but it only seems to have one month (I'm not sure which), instead of the 12 months of the year when I examine it using panoply.

Is it possible to write the NetCDF file and keep as much of the data from the R-grid file as possible? Especially the data for each month!

EDIT:

New working code:

test <- brick('/TavgM_1981.gri')
writeRaster(test, "rstack.nc", overwrite=TRUE, format="CDF",     varname="Temperature", varunit="degC", 
        longname="Temperature -- raster stack to netCDF", xname="Longitude",   yname="Latitude", zname="Time (Month)")

回答1:

As dww pointed out, to get all layers, this

test <- raster('.../TavgM_1981.gri', package = "raster")

should be

test <- brick('TavgM_1981.grd')

The main thing is to replace raster with brick. Also, the three dots .../ make no sense. It could be one or two dots (or unnecessary), and the package = "raster" argument is meaningless.