3

I wish to combine the "t" variable from the second .nc file, and use the lat, lon variables from the first .nc file as the lat and lon of the t variable, and store them to a new .nc file, that will have as variable the "t" and as lat and lon the "lat" and "lon" variables from the second .nc file. Until now, this is what I have managed to do:

library(ncdf4)
coords.nc = nc_open("coordinates.nc")
lat = ncvar_get(coords.nc, "lat")
lon = ncvar_get(coords.nc, "lon")
nc_close(coords.nc)

temp.nc = nc_open("temp.nc")
t = ncvar_get(temp.nc, "t")
nc_close(temp.nc)

# Define the dimensions and variables
dimX = ncdim_def("Long", "degrees", lon)
dimY = ncdim_def("Lat", "degrees", lat)
dimT = ncdim_def("t", "mm", pr)
varT = ncvar_def("t", "mm", dimT, t, prec = "float")

# Define missing value
mv = -9999

# Define the data
var1d = ncvar_def( "var1d", "units", dimX, mv, prec="float")
var2d = ncvar_def( "var2d", "units", list(dimX,dimY), mv, prec="float")
var3d = ncvar_def( "var3d", "units", list(dimX,dimY,dimT), mv,   prec="float")

# Create the NetCDF file
my_new_nc = nc_create("writevals.nc",  list(var1d, var2d, var3d)) 

# Write data to the NetCDF file
ncvar_put(my_new_nc, var3d, varT, start=c(1, 1, 1), count=c(1, 1, length(varT)))

# Close the new file to finish writing
nc_close(my_new_nc)

The code works fine until I reach the line for "nc_create":

nc = nc_create("writevals.nc",  list(var1d, var2d, var3d))

the error message I get is the following:

Error in R_nc4_enddef: NetCDF: One or more variable sizes violate  format constraints
Error in R_nc4_sync: NetCDF: Operation not allowed in define mode
Error in Rsx_nc4_put_vara_double: NetCDF: Operation not allowed in define mode
Error in ncdim_create(nc, d, verbose) : 
Error in ncdim_create, while writing dimvar values!

Could you please help me solve it?

  • I would recommend using the raster library, coercing into a raster object and then just using very straight forward operators, "calc" or "overlay" depending on exactly what you need to do. – Jeffrey Evans Dec 16 '16 at 17:11
  • where is 'pr' coming from? Also, try putting as.vector() around your initial ncvar_get() arguements, it'll return all the lat/lon/t data as vectors which you can plug into the new netcdf using ncvar_put – Sam Aug 10 '17 at 11:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.