[R] adding variable to netCDF file

Peter Ehlers ehlers at ucalgary.ca
Sun Sep 19 06:28:49 CEST 2010


On 2010-09-07 13:58, Cable, Samuel B Civ USAF AFMC AFRL/RVBXI wrote:
> I would like to open an existing netCDF file and add a variable to it.
> I am using the ncdf package.  This test code gives the idea of what I am
> trying to do:
>
> library(ncdf)
>
> print('here we go')
>
> print('first, construct netCDF file')
> t<-dim.def.ncdf('t','',1:1,unlim=T,create_dimvar=F)
> print('defining first vars')
> a<-var.def.ncdf('a','km',t,missval=-999)
> b<-var.def.ncdf('b','km',t,missval=-999)
>
> print('creating ncobj')
> ncobj<-create.ncdf('testfile.nc',list(a,b))
>
>
> print('adding data')
> put.var.ncdf(ncobj,a,c(1,2,3,4,5),count=5)
> put.var.ncdf(ncobj,b,c(10,20,30,40,50),count=5)
>
> print('file constructed.  close it.')
> close(ncobj)
>
> print('defining new var')
> c<-var.def.ncdf('c','hrs',t,missval=-999)
>
> print('now open file back up for adding variable')
> ncobj<-open.ncdf('testfile.nc',write=T)
>
> print('adding new var to ncobj')
> ncnewer<-var.add.ncdf(ncobj,c)
>
> print('new data')
> put.var.ncdf(ncnewer,c,c(.1,.2,.3,.4,.5))
>
> close.ncdf(ncnewer)
>
> Everything works fine until the call to var.add.ncdf(), where R stops
> with the very helpful error message "This is not allowed."  Anybody see
> what I am doing wrong?  Note that I am indeed calling open.ncdf() with
> write=T, as needed.  Thanks.
>

Sam,

I haven't seen an answer to this yet.
I don't know much about netCDF, but the following seems to work.
The main thing is, I think, that you need to re-define your 't'
to be in line with what's in testfile.nc.

  library(ncdf)
  t <- dim.def.ncdf('t','',1:1,unlim=TRUE,create_dimvar=FALSE)
  a <- var.def.ncdf('a','km',t,missval=-999)
  b <- var.def.ncdf('b','km',t,missval=-999)
  ncobj <- create.ncdf('testfile.nc',list(a,b))
  put.var.ncdf(ncobj,a,c(1,2,3,4,5),count=5)
  put.var.ncdf(ncobj,b,c(10,20,30,40,50),count=5)
  close(ncobj)

  ncobj <- open.ncdf('testfile.nc',write=TRUE)
  t <- ncobj$dim[['t']]
  c <- var.def.ncdf('c','hrs',t,missval=-999)
  ncobj <- var.add.ncdf(ncobj,c)
  close(ncobj)

  tmp <- open.ncdf('testfile.nc',write=TRUE)
  put.var.ncdf(tmp,c,c(.1,.2,.3,.4,.5))
  close(tmp)


   -Peter Ehlers



More information about the R-help mailing list