mjwoods / RNetCDF

Read and write netcdf format in R
Other
24 stars 9 forks source link

Getting variable names from netCDF file #114

Closed half-normal closed 1 year ago

half-normal commented 1 year ago

Hi I am wondering how to get the names of all variables in a netCDF file. In ncdf4 this is easy with:

nc <- nc_open("someFile.nc") names(nc$var)

Is there an equivalent method in RNetCDF?

mjwoods commented 1 year ago

Hi @bfordAIMS , RNetCDF mainly aims to provide a low-level interface to the NetCDF C library, so it lacks some of the convenience of ncdf4. But it has some advantages too, by exposing more functionality of the C library and allowing access to more advanced data types.

The simplest equivalent to names(nc$var) in RNetCDF is:

names(read.nc(nc, recursive=FALSE))

Please note that this command also reads the contents of variables, which you may want to avoid for large files.

To read only the variable names in RNetCDF, you could do this:

sapply(seq_len(file.inq.nc$nvars), function(x) {var.inq.nc(nc, x-1)$name})

It involves first finding the number of variables using file.inq.nc, then looping through the variables by numeric identifier to find their names with var.inq.nc.

If your file uses groups, the above command will only show variables in the root group. To see all the variables, you could write a recursive function using the code for read.nc as a guide: https://github.com/mjwoods/RNetCDF/blob/master/R/RNetCDF.R

half-normal commented 1 year ago

Thank you @mjwoods! This is great.

mjwoods commented 1 year ago

Thanks @bfordAIMS , I will close the issue, but please feel free to ask further questions here if needed.