How to extract variable names from a netCDF file in R?
Asked Answered
M

2

16

I am writing a function in R to extract some air quality modelling data from netCDF files. I have the Package "ncdf" installed.

In order to allow other users or myself to choose what variables to extract from a netCDF file, I would like to extract the names of all variables in the file, so that I can present in a simple list rather than just print.ncdf() the file to give too much information. Is there any way of doing it?

I tried unlist() to the var field of the ncdf object but it seemed that it returned the contents as well...

I googled and searched stack*overflow* but didn't seem to find an answer, so your help is very much appreciated.

Many thanks in advance.

Marcus answered 29/1, 2013 at 15:33 Comment(0)
I
28

If your ncdf object is called nc, then quite simply:

names(nc$var)

With an example, using the dataset downloaded here, for instance (since you didn't provide with one):

nc <- open.ncdf("20130128-ABOM-L4HRfnd-AUS-v01-fv01_0-RAMSSA_09km.nc")
names(nc$var)
[1] "analysed_sst"     "analysis_error"   "sea_ice_fraction" "mask"   
Intercolumniation answered 29/1, 2013 at 15:47 Comment(1)
Thanks very much, @Intercolumniation - I should have thought of this! Sorry for not providing an example file, as I am pretty new to R and netCDF, I thought I couldn't copy my working file which is ~35 GB to illustrate... ;-)Marcus
C
8

It is now 2016. ncdf package is deprecated. Same code as SE user plannapus' answer is now:

library(ncdf4)
netcdf.file <- "flux.nc"
nc = ncdf4::nc_open(netcdf.file)
variables = names(nc[['var']])
#print(nc)

A note from the documentation:

Package: ncdf
Title: Interface to Unidata netCDF Data Files
Maintainer: Brian Ripley <[email protected]>
Version: 1.6.9
Author: David Pierce <[email protected]>
Description: This is deprecated and will be removed
   from CRAN in early 2016: use 'RNetCDF' or 'ncdf4' instead.

Newer package "ncdf4" is designed to work with the netcdf library 
version 4, and supports features such as compression and 
chunking.Unfortunately, for various reasons the ncdf4 package must have
a different API than the ncdf package.

A note from the home page of the maintainer:

Package ncdf4 -- use this for new code

The "ncdf4" package is designed to work with the netcdf library, version 4. 
It includes the ability to use compression and chunking, 
which seem to be some of the most anticipated benefits of the version 4 
library. Note that the API of ncdf4 has to be different 
from the API of ncdf, unfortunately. New code should use ncdf4, not ncdf. 

http://cirrus.ucsd.edu/~pierce/ncdf/

Cantara answered 8/2, 2016 at 14:51 Comment(1)
How can we know the name of "default" variable ncvar_get would return? It is not the first one in the list from names(nc$var).Artis

© 2022 - 2024 — McMap. All rights reserved.