Learn R Programming

metR (version 0.3.0)

ReadNetCDF: Read NetCDF files.

Description

Using the ncdf4-package package, it reads a NetCDF file. The advantage over using ncvar_get is that the output is a tidy data.table with proper dimensions.

Usage

ReadNetCDF(file, vars = NULL, out = c("data.frame", "vector", "array",
  "vars"), subset = NULL, key = FALSE)

Arguments

file

file to read from.

vars

a character vector with the name of the variables to read. If NULL, then it read all the variables.

out

character indicating the type of output desired

subset

a named list a subsetting vectors. See Details.

key

if TRUE, returns a data.table keyed by the dimensions of the data.

Value

The return format is specified by out. It can be a data table in which each column is a variable and each row, an observation; an array with named dimensions; or a vector. Since it's possible to return multiple arrays or vectors (one for each variable), for consistency the return type is always a list. Either of these two options are much faster than the first since the most time consuming part is the melting of the array returned by ncdf4::ncvar_get. out = "vector" is particularly useful for adding new variables to an existing data frame with the same dimensions.

Finally, it can also be vars, in which case it returns a list with the name of the available variables and the dimensions of the spatiotemporal grid.

When not all variables specified in vars have the same number of dimensions, the shorter variables will be recycled. E.g. if reading a 3D pressure field and a 2D surface temperature field, the latter will be turned into a 3D field with the same values in each missing dimension.

Details

subset must be a named list for subsetting. Names must match dimensions specified in the NetCDF file and each element must be a vector of the same type of that dimension whose range will be use for subsetting. You don't need to provide and exact range that matches the actual gridpoints of the file; the closest gridpoint will be selected.

Examples

Run this code
# NOT RUN {
file <- "file.nc"
# Get a list of variables.
variables <- ReadNetCDF(file, out = "vars")
# Read only the first one, with name "var".
field <- ReadNetCDF(file, vars = c(var = variables$vars[1]))
# Add a new variable.
# <U+00A1>Make sure it's on the same exact grid!
field[, var2 := ReadNerCDF(file2, out = "vector", subset = list(lat = 90:10))]
# }
# NOT RUN {
# }

Run the code above in your browser using DataLab