Reputation: 192
I created a NetCDF file with a number of variables in it. While debugging and testing writing out new variables to the files I created the variable 'RH' in some files, but the majority still have no 'RH' in them. Now I want to run my script that will cycle through all my files and put the data into the RH variable where it exists, or just add the variable, then the data, where it doesn't already exist.
library(ncdf4)
#Open the original file with my variables in it
ncid_old <- nc_open("original.nc"), write=TRUE )
#Create the 'RH' variable and put it in the file
var <- ncvar_def( 'RH', '%', list(xdim2,ydim2,tdim2), mv2 )
ncid_old <- ncvar_add( ncid_old, var)
If the variable already exists (as is does in some cases) I get this error:
Error in R_nc4_def_var_float: NetCDF: String match to name in use
Name of variable that the error occurred on: "RH"
I.e., you are trying to add a variable with that name to the file, but it ALREADY has a variable with that name!
How can I first check if the variable 'RH' exists? Then I can just include an if statement in my r script to check if it exists and if it does already, then I don't include the line:
ncid_old <- ncvar_add( ncid_old, var)
Instead I just go straight to adding the data to the variable:
ncvar_put( ncid_old, var, RHdata, start=c(1,1,1), count=c(nx,ny,12))
Upvotes: 0
Views: 1108