3

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)")
Pad
  • 841
  • 2
  • 17
  • 45
  • 1
    The link to the grid file is broken. I'm almost certain your problem is that `test <- raster(...)` only creates a single raster layer. So when you use stack on it you still have a single layer only. The solution is to load the grid file as a `brick` in the first place. But I'd like to check this before posting an answer, if you can fix the link. – dww Apr 25 '18 at 17:43
  • have now fixed the links - sorry, site must not host for long – Pad Apr 25 '18 at 20:06

1 Answers1

3

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.

Robert Hijmans
  • 40,301
  • 4
  • 55
  • 63
  • Thank you! I am now trying to convert the x and y coordinates from 'meters' in the Raster file to lat/lon. – Pad Apr 26 '18 at 09:36