I would like to write a netCDF file using R with 'unlimited' dimensions that I can later extend.
This is what I have tried:
Create a netcdf file
library(ncdf4)
## define lat, lon time dimensions
lat <- ncdim_def("latitude", "degrees_east", vals = 44.0, unlim = TRUE)
lon <- ncdim_def("longitude", "degrees_north", vals = -88.5, unlim = TRUE)
time <- ncdim_def("time", "days since 0000-01-01", 1:1000)
## define data with these dimensions
x <- ncvar_def("myvar", units = "m2", dim = list(lat, lon, time))
## create, write to, close nc file
nc <- nc_create(filename = "tmp.nc", vars = list(x))
ncvar_put(nc = nc, varid = x, vals = 1:1000)
nc_close(nc = nc)
I want to add a new vector at a different lat and lon
## reopen existing file
nc <- nc_open("tmp.nc", write = TRUE)
## define new lat, lon dimensions (keep time dim from above)
lat2 <- ncdim_def("latitude", "degrees_east", vals = 44.5, unlim = TRUE)
lon2 <- ncdim_def("longitude", "degrees_north", vals = -89.0, unlim = TRUE)
## define, write new dataset at new lat lon coordinates
x2 <- ncvar_def("myvar", units = "m2", dim = list(lat2, lon2, time))
ncvar_put(nc = nc, varid = x2, vals = 11:1011)
I would expect to find the two different latitudes and longitudes
ncvar_get(nc, 'latitude')
ncvar_get(nc, 'longitude')
ncvar_get(nc, 'myvar')
These show that the file was written using the first set of lat/lon and 'myvar' values, but was not appended with the new set of values.
What am I doing wrong?
I know that the ability to have multiple unlimited dimensions, and to add to them, is a feature of netCDF-4. How can I do this in R?
I recognize that I must be confusing the 'dimension definition' with some other concept. But I am a bit lost.