| Title: | Tools for Manipulating netCDF Files |
|---|---|
| Description: | Provides helper functions for creating, editing, subsetting, concatenating, and transforming netCDF files. The package includes utilities for writing arrays to netCDF, renaming variables and dimensions, changing longitude conventions, and applying summary functions over dimensions through 'ncdf4'. |
| Authors: | Ricardo Oliveros-Ramos [aut, cre] (ORCID: <https://orcid.org/0000-0002-8069-2101>) |
| Maintainer: | Ricardo Oliveros-Ramos <[email protected]> |
| License: | GPL-3 |
| Version: | 0.2.0 |
| Built: | 2026-11-19 22:28:23 UTC |
| Source: | https://github.com/cran/nctools |
Converts longitude values to either the [-180, 180] convention or the
[0, 360] convention.
checkLongitude(x, primeMeridian = "center", sort = FALSE, ...)checkLongitude(x, primeMeridian = "center", sort = FALSE, ...)
x |
Numeric vector of longitude values. |
primeMeridian |
Character string specifying the target longitude
convention. Use |
sort |
Logical. If |
... |
Additional arguments. Currently unused. |
Longitude values are modified only when needed. For primeMeridian = "center", values greater than 180 are shifted by subtracting 360. For
primeMeridian = "left", negative values are shifted by adding 360.
A numeric vector of longitude values expressed in the requested convention.
local({ checkLongitude(c(-80, -70, -60), primeMeridian = "left") })local({ checkLongitude(c(-80, -70, -60), primeMeridian = "left") })
Infers whether a longitude vector is expressed using the [-180, 180]
convention or the [0, 360] convention.
findPrimeMeridian(x)findPrimeMeridian(x)
x |
Numeric vector of longitude values. |
The function returns "center" if any longitude is negative, and "left"
if any longitude is greater than 180. If neither condition is met, the
convention cannot be determined unambiguously and the function returns
NULL with a warning.
A character string, either "center" or "left", or NULL if the
convention cannot be determined.
local({ findPrimeMeridian(c(-80, -70, -60)) })local({ findPrimeMeridian(c(-80, -70, -60)) })
Reads a variable from a netCDF file, applies a function over one or more of
its dimensions using base::apply(), and writes the result to a new netCDF
file.
nc_apply( filename, varid, MARGIN, FUN, ..., output = NULL, drop = FALSE, newdim = NULL, name = NULL, longname = NULL, units = NULL, compression = NA, verbose = FALSE, force_v4 = TRUE, ignore.case = FALSE )nc_apply( filename, varid, MARGIN, FUN, ..., output = NULL, drop = FALSE, newdim = NULL, name = NULL, longname = NULL, units = NULL, compression = NA, verbose = FALSE, force_v4 = TRUE, ignore.case = FALSE )
filename |
Character string giving the path to the input netCDF file. |
varid |
Character string giving the name of the variable to process. If missing and the file contains a single variable, that variable is used. |
MARGIN |
Integer or character vector specifying the dimensions to retain
in the output, as in |
FUN |
Function to apply. |
... |
Additional arguments passed to |
output |
Character string giving the path to the output netCDF file to create. |
drop |
Logical. Currently not implemented. |
newdim |
Optional numeric values for the dimension created when |
name |
Optional character string giving the name of the output variable. By default, the original variable name is used. |
longname |
Optional character string giving the long name of the output
variable. By default, a name based on |
units |
Optional character string giving the units of the output variable. By default, the units of the input variable are used. |
compression |
Optional numeric compression level for the output variable. |
verbose |
Logical. Currently unused. |
force_v4 |
Logical. Currently unused internally. |
ignore.case |
Logical. If |
The selected variable is read into memory and processed with base::apply().
The output retains the dimensions specified in MARGIN. If FUN returns a
vector of length greater than one, an additional dimension is appended to the
result; its coordinate values are taken from newdim when provided, or
generated automatically otherwise.
Invisibly returns output.
nc_subset(), write_ncdf(), base::apply()
local({ input = system.file("extdata", "temperature_2001_01.nc", package = "nctools", mustWork = TRUE) output = tempfile(fileext = ".nc") on.exit(unlink(output)) nc_apply(input, "temperature", MARGIN = "time", FUN = mean, na.rm = TRUE, output = output) })local({ input = system.file("extdata", "temperature_2001_01.nc", package = "nctools", mustWork = TRUE) output = tempfile(fileext = ".nc") on.exit(unlink(output)) nc_apply(input, "temperature", MARGIN = "time", FUN = mean, na.rm = TRUE, output = output) })
Reorders the longitude dimension of a variable so that longitudes follow
either the [-180, 180] convention or the [0, 360] convention, and writes
the result to a netCDF file.
nc_changePrimeMeridian( filename, output, varid = NA, MARGIN = 1, primeMeridian = "center", verbose = FALSE, overwrite = FALSE, compression = NA, mem.limit = 3072, ignore.case = FALSE )nc_changePrimeMeridian( filename, output, varid = NA, MARGIN = 1, primeMeridian = "center", verbose = FALSE, overwrite = FALSE, compression = NA, mem.limit = 3072, ignore.case = FALSE )
filename |
Character string giving the path to the input netCDF file. |
output |
Optional character string giving the path to the output
netCDF file. If omitted, |
varid |
Variable identifier. This can be a character string giving the variable name. If omitted and the file contains a single variable, that variable is used. |
MARGIN |
Integer or character string of length one specifying the longitude dimension. This can be either the dimension index or its name. |
primeMeridian |
Character string specifying the target longitude
convention. Use |
verbose |
Logical. If |
overwrite |
Logical. If |
compression |
Optional numeric compression level for the output variable. Supplying this typically requires netCDF4 output. |
mem.limit |
Numeric. Approximate memory limit, in MiB, used when processing large variables. If the variable exceeds this limit, it is reordered iteratively in chunks. |
ignore.case |
Logical. If |
The function updates the longitude coordinate values of the selected variable, reorders the data accordingly, and writes the result to a new netCDF file. If the variable is small enough, the full array is processed in memory. Otherwise, the variable is processed iteratively in chunks to reduce memory use.
If the longitude values already follow the requested convention, the function
returns with a warning. When output differs from filename, the input file
is copied to output unchanged.
Invisibly returns output.
local({ input = system.file("extdata", "temperature_2001_01.nc", package = "nctools", mustWork = TRUE) output = tempfile(fileext = ".nc") on.exit(unlink(output)) nc_changePrimeMeridian(input, output, varid = "temperature", primeMeridian = "left") })local({ input = system.file("extdata", "temperature_2001_01.nc", package = "nctools", mustWork = TRUE) output = tempfile(fileext = ".nc") on.exit(unlink(output)) nc_changePrimeMeridian(input, output, varid = "temperature", primeMeridian = "left") })
Creates a new netCDF file containing a single variable copied from an existing file.
nc_extract(filename, varid, output)nc_extract(filename, varid, output)
filename |
Character string giving the path to the input netCDF file. |
varid |
Character string giving the name of the variable to extract. If missing and the file contains a single variable, that variable is used. |
output |
Character string giving the path to the output netCDF file to create. |
Invisibly returns output.
write_ncdf(), nc_subset(), nc_apply()
local({ input = system.file("extdata", "temperature_2001_01.nc", package = "nctools", mustWork = TRUE) output = tempfile(fileext = ".nc") on.exit(unlink(output)) nc_extract(input, "temperature", output) })local({ input = system.file("extdata", "temperature_2001_01.nc", package = "nctools", mustWork = TRUE) output = tempfile(fileext = ".nc") on.exit(unlink(output)) nc_extract(input, "temperature", output) })
Finds the position along one dimension of a netCDF variable where the
variable reaches a target value, and writes the result to a new netCDF file.
In the typical use case, this is used to estimate the depth at which a
variable equals loc, using linear interpolation between adjacent depth
levels when needed.
nc_loc( filename, varid, MARGIN, loc, output = NULL, drop = TRUE, newdim = NULL, name = NULL, longname = NULL, units = NULL, compression = NA, verbose = FALSE, force_v4 = TRUE, ignore.case = FALSE )nc_loc( filename, varid, MARGIN, loc, output = NULL, drop = TRUE, newdim = NULL, name = NULL, longname = NULL, units = NULL, compression = NA, verbose = FALSE, force_v4 = TRUE, ignore.case = FALSE )
filename |
Character string. Path to the input netCDF file. |
varid |
Character string. Name of the variable to analyse. If missing and the file contains only one variable, that variable is used. |
MARGIN |
Integer or character string of length one. Dimension along
which the target value is searched. This can be either the dimension index
or its name (for example |
loc |
Numeric. Target value to locate in the variable. |
output |
Character string. Path to the output netCDF file to create. |
drop |
Logical. Should degenerate dimensions be dropped? Currently not used internally. |
newdim |
Reserved for future use. Currently not used internally. |
name |
Character string. Name of the output variable. By default, the name of the searched dimension is used. |
longname |
Character string. Long name for the output variable. By default, a descriptive name is generated automatically. |
units |
Character string. Units for the output variable. Currently not used internally; by default, the units of the searched dimension are used. |
compression |
Numeric. Compression level for the output variable. If not
|
verbose |
Logical. Should extra information be printed? Currently not used internally. |
force_v4 |
Logical. Should the output file be forced to netCDF4? Currently not used internally. |
ignore.case |
Logical. Ignore case when matching the dimension name in
|
The function searches for the first sign change in
variable - loc along the selected dimension, then estimates the exact
position by linear interpolation between the two surrounding grid points.
The output file contains a new variable with the searched dimension removed.
For example, if MARGIN corresponds to depth, the output is a field giving
the estimated depth at which varid reaches loc for each remaining
combination of dimensions.
Invisibly returns the path to the created output file.
local({ input = system.file("extdata", "temperature_profile.nc", package = "nctools", mustWork = TRUE) output = tempfile(fileext = ".nc") on.exit(unlink(output)) # Locate the 20 degree isotherm using linear interpolation in depth nc_loc(input, "temperature", MARGIN = "depth", loc = 20, output = output) nc = ncdf4::nc_open(output) result = tryCatch({ list(lon = ncdf4::ncvar_get(nc, "lon"), lat = ncdf4::ncvar_get(nc, "lat"), depth = ncdf4::ncvar_get(nc, "depth")) }, finally = ncdf4::nc_close(nc)) # The input profiles follow T(z) = 8 + (surface - 8) * exp(-z / scale) surface = outer(result$lon, result$lat, function(x, y) 24 + 3 * exp(-((x + 72)^2 / 16 + (y + 15)^2 / 36)) + (y + 25) / 19) scale = outer(result$lon, result$lat, function(x, y) 50 + 25 * ((x + 80) / 15 + (y + 25) / 19)) analytical = scale * log((surface - 8) / (20 - 8)) analytical[1:2, 1:2] = NA_real_ # Interpolation on 10 m depth intervals approximates the exact solution error = result$depth - analytical print(range(error, na.rm = TRUE)) # signed interpolation error in metres print(max(abs(error), na.rm = TRUE)) image(result$lon, result$lat, result$depth, xlab = "Longitude", ylab = "Latitude", main = "Depth of the 20 degree isotherm (m)") contour(result$lon, result$lat, analytical, add = TRUE) # Contours show the analytical depth; the missing corner remains blank })local({ input = system.file("extdata", "temperature_profile.nc", package = "nctools", mustWork = TRUE) output = tempfile(fileext = ".nc") on.exit(unlink(output)) # Locate the 20 degree isotherm using linear interpolation in depth nc_loc(input, "temperature", MARGIN = "depth", loc = 20, output = output) nc = ncdf4::nc_open(output) result = tryCatch({ list(lon = ncdf4::ncvar_get(nc, "lon"), lat = ncdf4::ncvar_get(nc, "lat"), depth = ncdf4::ncvar_get(nc, "depth")) }, finally = ncdf4::nc_close(nc)) # The input profiles follow T(z) = 8 + (surface - 8) * exp(-z / scale) surface = outer(result$lon, result$lat, function(x, y) 24 + 3 * exp(-((x + 72)^2 / 16 + (y + 15)^2 / 36)) + (y + 25) / 19) scale = outer(result$lon, result$lat, function(x, y) 50 + 25 * ((x + 80) / 15 + (y + 25) / 19)) analytical = scale * log((surface - 8) / (20 - 8)) analytical[1:2, 1:2] = NA_real_ # Interpolation on 10 m depth intervals approximates the exact solution error = result$depth - analytical print(range(error, na.rm = TRUE)) # signed interpolation error in metres print(max(abs(error), na.rm = TRUE)) image(result$lon, result$lat, result$depth, xlab = "Longitude", ylab = "Latitude", main = "Depth of the 20 degree isotherm (m)") contour(result$lon, result$lat, analytical, add = TRUE) # Contours show the analytical depth; the missing corner remains blank })
Applies a summary function to a variable in a netCDF file over the
dimensions not listed in MARGIN, and writes the result to a new netCDF
file.
nc_mean( filename, varid, MARGIN = c(1, 2), na.rm = TRUE, trim = 0, output = NULL, drop = TRUE, compression = NA, verbose = FALSE, force_v4 = TRUE, ignore.case = FALSE ) nc_min( filename, varid, MARGIN = c(1, 2), na.rm = TRUE, output = NULL, drop = TRUE, compression = NA, verbose = FALSE, force_v4 = TRUE, ignore.case = FALSE ) nc_max( filename, varid, MARGIN = c(1, 2), na.rm = TRUE, output = NULL, drop = TRUE, compression = NA, verbose = FALSE, force_v4 = TRUE, ignore.case = FALSE )nc_mean( filename, varid, MARGIN = c(1, 2), na.rm = TRUE, trim = 0, output = NULL, drop = TRUE, compression = NA, verbose = FALSE, force_v4 = TRUE, ignore.case = FALSE ) nc_min( filename, varid, MARGIN = c(1, 2), na.rm = TRUE, output = NULL, drop = TRUE, compression = NA, verbose = FALSE, force_v4 = TRUE, ignore.case = FALSE ) nc_max( filename, varid, MARGIN = c(1, 2), na.rm = TRUE, output = NULL, drop = TRUE, compression = NA, verbose = FALSE, force_v4 = TRUE, ignore.case = FALSE )
filename |
Character string giving the path to the input netCDF file. |
varid |
Character string giving the name of the variable to process. If missing and the file contains a single variable, that variable is used. |
MARGIN |
Integer or character vector specifying the dimensions to retain
in the output, as in |
na.rm |
Logical. If |
trim |
Numeric scalar giving the fraction of observations to be trimmed
from each end before computing the mean. Passed to |
output |
Character string giving the path to the output netCDF file to create. |
drop |
Logical. Currently not implemented. |
compression |
Optional numeric compression level for the output variable. |
verbose |
Logical. Currently unused. |
force_v4 |
Logical. Currently unused internally. |
ignore.case |
Logical. If |
nc_mean() applies base::mean(), nc_min() applies base::min(), and
nc_max() applies base::max().
The output retains the dimensions specified in MARGIN.
Invisibly returns output.
nc_apply(), base::mean(), base::min(), base::max()
local({ input = system.file("extdata", "temperature_2001_01.nc", package = "nctools", mustWork = TRUE) output = tempfile(fileext = ".nc") on.exit(unlink(output)) nc_mean(input, "temperature", MARGIN = c("lon", "lat"), output = output) })local({ input = system.file("extdata", "temperature_2001_01.nc", package = "nctools", mustWork = TRUE) output = tempfile(fileext = ".nc") on.exit(unlink(output)) nc_mean(input, "temperature", MARGIN = c("lon", "lat"), output = output) })
Applies stats::quantile() to a variable in a netCDF file over the
dimensions not listed in MARGIN, and writes the result to a new netCDF
file.
nc_quantile( filename, varid, MARGIN = c(1, 2), na.rm = TRUE, probs = c(0, 0.5, 1), output = NULL, drop = TRUE, compression = NA, verbose = FALSE, force_v4 = TRUE, ignore.case = FALSE )nc_quantile( filename, varid, MARGIN = c(1, 2), na.rm = TRUE, probs = c(0, 0.5, 1), output = NULL, drop = TRUE, compression = NA, verbose = FALSE, force_v4 = TRUE, ignore.case = FALSE )
filename |
Character string giving the path to the input netCDF file. |
varid |
Character string giving the name of the variable to process. If missing and the file contains a single variable, that variable is used. |
MARGIN |
Integer or character vector specifying the dimensions to retain
in the output, as in |
na.rm |
Logical. If |
probs |
Numeric vector of probabilities in |
output |
Character string giving the path to the output netCDF file to create. |
drop |
Logical. Currently not implemented. |
compression |
Optional numeric compression level for the output variable. |
verbose |
Logical. Currently unused. |
force_v4 |
Logical. Currently unused internally. |
ignore.case |
Logical. If |
The output retains the dimensions specified in MARGIN. An additional
dimension is appended to store the quantiles defined by probs.
Invisibly returns output.
local({ input = system.file("extdata", "temperature_2001_01.nc", package = "nctools", mustWork = TRUE) output = tempfile(fileext = ".nc") on.exit(unlink(output)) nc_quantile(input, "temperature", MARGIN = c("lon", "lat"), output = output) })local({ input = system.file("extdata", "temperature_2001_01.nc", package = "nctools", mustWork = TRUE) output = tempfile(fileext = ".nc") on.exit(unlink(output)) nc_quantile(input, "temperature", MARGIN = c("lon", "lat"), output = output) })
Concatenates the records of the same variable from multiple netCDF files along the unlimited dimension and writes the result to a new file.
nc_rcat(filenames, varid, output)nc_rcat(filenames, varid, output)
filenames |
Character vector with the paths to the input netCDF files. |
varid |
Character string giving the name of the variable to concatenate. If missing, the variable is inferred from the first file when possible. |
output |
Character string giving the path to the output netCDF file to create. |
All files must contain the selected variable and must be compatible in all
non-unlimited dimensions. The unlimited dimension is appended in the order
given by filenames.
Invisibly returns output.
local({ input = system.file("extdata", "temperature_2001_01.nc", package = "nctools", mustWork = TRUE) output = tempfile(fileext = ".nc") on.exit(unlink(output)) files = system.file("extdata", sprintf("temperature_2001_%02d.nc", 1:3), package = "nctools", mustWork = TRUE) first = tempfile(fileext = ".nc") on.exit(unlink(first), add = TRUE) nc_rcat(files[1:2], "temperature", first) nc_rcat(c(first, files[3]), "temperature", output) })local({ input = system.file("extdata", "temperature_2001_01.nc", package = "nctools", mustWork = TRUE) output = tempfile(fileext = ".nc") on.exit(unlink(output)) files = system.file("extdata", sprintf("temperature_2001_%02d.nc", 1:3), package = "nctools", mustWork = TRUE) first = tempfile(fileext = ".nc") on.exit(unlink(first), add = TRUE) nc_rcat(files[1:2], "temperature", first) nc_rcat(c(first, files[3]), "temperature", output) })
Renames one or more variables and/or dimensions in an existing netCDF file, optionally writing the result to a new file.
nc_rename( filename, oldnames, newnames, output, verbose = FALSE, overwrite = FALSE )nc_rename( filename, oldnames, newnames, output, verbose = FALSE, overwrite = FALSE )
filename |
Character string giving the path to the input netCDF file. |
oldnames |
Character vector with the current names of variables or dimensions to rename. |
newnames |
Character vector with the replacement names. Must be in the
same order and of the same length as |
output |
Optional character string giving the path to the output file.
If omitted, |
verbose |
Logical. If |
overwrite |
Logical. If |
Names in oldnames that do not match either a variable or a dimension in the
file are ignored with a warning. If none of the requested names are found,
the function exits without making changes.
Invisibly returns the path to the modified file, or NULL
invisibly if nothing was changed.
local({ input = system.file("extdata", "temperature_2001_01.nc", package = "nctools", mustWork = TRUE) output = tempfile(fileext = ".nc") on.exit(unlink(output)) nc_rename(input, "temperature", "temp", output = output) })local({ input = system.file("extdata", "temperature_2001_01.nc", package = "nctools", mustWork = TRUE) output = tempfile(fileext = ".nc") on.exit(unlink(output)) nc_rename(input, "temperature", "temp", output = output) })
Extracts a subset of a variable from a netCDF file using coordinate bounds supplied for one or more dimensions, and writes the result to a new file.
nc_subset( filename, varid, output, newvarid, compression, force_v4 = FALSE, ..., ignore.case = FALSE, drop = FALSE )nc_subset( filename, varid, output, newvarid, compression, force_v4 = FALSE, ..., ignore.case = FALSE, drop = FALSE )
filename |
Character string giving the path to the input netCDF file. |
varid |
Character string giving the name of the variable to subset. If missing and the file contains a single variable, that variable is used. |
output |
Character string giving the path to the output netCDF file to create. |
newvarid |
Optional character string giving the name of the variable in the output file. By default, the original variable name is used. |
compression |
Optional numeric compression level for the output variable. Supplying this typically requires netCDF4 output. |
force_v4 |
Logical. If |
... |
Named bounds for dimensions to subset. Each argument name must
match a dimension name. Values should be numeric vectors of length two
giving lower and upper bounds. A length-one value is treated as an exact
coordinate and expanded internally to |
ignore.case |
Logical. If |
drop |
Logical. If |
Only dimensions named in ... are subset; all others are kept in full. The
output file contains the subsetted variable, with updated dimension values.
Global attributes from the source file are copied to the output file, and the
global history attribute is updated with the function call.
Invisibly returns output, or NULL invisibly if none of the
supplied dimension names match the variable dimensions.
local({ input = system.file("extdata", "temperature_2001_01.nc", package = "nctools", mustWork = TRUE) output = tempfile(fileext = ".nc") on.exit(unlink(output)) nc_subset(input, "temperature", output, lon = c(-75, -70), lat = c(-20, -10)) })local({ input = system.file("extdata", "temperature_2001_01.nc", package = "nctools", mustWork = TRUE) output = tempfile(fileext = ".nc") on.exit(unlink(output)) nc_subset(input, "temperature", output, lon = c(-75, -70), lat = c(-20, -10)) })
Recreates a netCDF file with the selected dimension marked as unlimited.
nc_unlim(filename, unlim, output = NULL)nc_unlim(filename, unlim, output = NULL)
filename |
Character string giving the path to the input netCDF file. |
unlim |
Character string giving the name of the dimension to set as unlimited. |
output |
Optional character string giving the path to the output file.
If |
The function rebuilds the file definition with the requested dimension marked as unlimited in every variable where that dimension is present, then copies the variable values to the new file.
Invisibly returns the list of variable definitions used to create the new file.
local({ input = system.file("extdata", "temperature_2001_01.nc", package = "nctools", mustWork = TRUE) output = tempfile(fileext = ".nc") on.exit(unlink(output)) nc = ncdf4::nc_open(input) x = tryCatch(ncdf4::ncvar_get(nc, "temperature"), finally = ncdf4::nc_close(nc)) fixed = tempfile(fileext = ".nc") on.exit(unlink(fixed), add = TRUE) write_ncdf(x, fixed, "temperature", dim = list(lon = seq(-80, -65, length.out = 15), lat = seq(-25, -6, length.out = 20), time = 0:30), compression = NA) nc_unlim(fixed, "time", output) })local({ input = system.file("extdata", "temperature_2001_01.nc", package = "nctools", mustWork = TRUE) output = tempfile(fileext = ".nc") on.exit(unlink(output)) nc = ncdf4::nc_open(input) x = tryCatch(ncdf4::ncvar_get(nc, "temperature"), finally = ncdf4::nc_close(nc)) fixed = tempfile(fileext = ".nc") on.exit(unlink(fixed), add = TRUE) write_ncdf(x, fixed, "temperature", dim = list(lon = seq(-80, -65, length.out = 15), lat = seq(-25, -6, length.out = 20), time = 0:30), compression = NA) nc_unlim(fixed, "time", output) })
Returns all attributes associated with variables or dimensions in an open netCDF file.
ncatt_get_all(nc, type = c("var", "dim"))ncatt_get_all(nc, type = c("var", "dim"))
nc |
An open netCDF connection created with |
type |
Character string indicating whether to return attributes for
variables ( |
A named list of attribute lists.
ncatt_put_all(), ncdf4::ncatt_get()
local({ input = system.file("extdata", "temperature_2001_01.nc", package = "nctools", mustWork = TRUE) copy = tempfile(fileext = ".nc") file.copy(input, copy) nc = ncdf4::nc_open(copy, write = TRUE) on.exit({ ncdf4::nc_close(nc); unlink(copy) }, add = TRUE) ncatt_get_all(nc) })local({ input = system.file("extdata", "temperature_2001_01.nc", package = "nctools", mustWork = TRUE) copy = tempfile(fileext = ".nc") file.copy(input, copy) nc = ncdf4::nc_open(copy, write = TRUE) on.exit({ ncdf4::nc_close(nc); unlink(copy) }, add = TRUE) ncatt_get_all(nc) })
Writes several attributes to a variable or to the global file metadata of an open netCDF file.
ncatt_put_all( nc, varid, attname, attval, prec = NA, verbose = FALSE, definemode = FALSE )ncatt_put_all( nc, varid, attname, attval, prec = NA, verbose = FALSE, definemode = FALSE )
nc |
An open netCDF connection created with |
varid |
Variable identifier. This can be a character string giving the
variable name, an object of class |
attname |
Names of the attributes to write. Alternatively, this may be a
named vector or list of attribute values when |
attval |
Values of the attributes to write. If omitted, |
prec |
Optional precision used when writing the attributes. Passed to
|
verbose |
Logical. If |
definemode |
Logical. Passed to |
Attributes can be supplied either as parallel attname and attval
arguments, or as a single named vector or list. Missing attribute names are
not allowed.
NULL, invisibly.
ncatt_get_all(), ncdf4::ncatt_put()
local({ input = system.file("extdata", "temperature_2001_01.nc", package = "nctools", mustWork = TRUE) copy = tempfile(fileext = ".nc") file.copy(input, copy) nc = ncdf4::nc_open(copy, write = TRUE) on.exit({ ncdf4::nc_close(nc); unlink(copy) }, add = TRUE) ncatt_put_all(nc, 0, attval = list(title = "Edited copy")) })local({ input = system.file("extdata", "temperature_2001_01.nc", package = "nctools", mustWork = TRUE) copy = tempfile(fileext = ".nc") file.copy(input, copy) nc = ncdf4::nc_open(copy, write = TRUE) on.exit({ ncdf4::nc_close(nc); unlink(copy) }, add = TRUE) ncatt_put_all(nc, 0, attval = list(title = "Edited copy")) })
Returns whether each dimension in an open netCDF file is unlimited.
ncdim_isUnlim(nc)ncdim_isUnlim(nc)
nc |
An open netCDF connection created with |
A named logical vector indicating whether each dimension is unlimited.
local({ input = system.file("extdata", "temperature_2001_01.nc", package = "nctools", mustWork = TRUE) copy = tempfile(fileext = ".nc") file.copy(input, copy) nc = ncdf4::nc_open(copy, write = TRUE) on.exit({ ncdf4::nc_close(nc); unlink(copy) }, add = TRUE) ncdim_isUnlim(nc) })local({ input = system.file("extdata", "temperature_2001_01.nc", package = "nctools", mustWork = TRUE) copy = tempfile(fileext = ".nc") file.copy(input, copy) nc = ncdf4::nc_open(copy, write = TRUE) on.exit({ ncdf4::nc_close(nc); unlink(copy) }, add = TRUE) ncdim_isUnlim(nc) })
Returns the lengths of all dimensions in an open netCDF file.
ncdim_size(nc)ncdim_size(nc)
nc |
An open netCDF connection created with |
A named list giving the length of each dimension.
local({ input = system.file("extdata", "temperature_2001_01.nc", package = "nctools", mustWork = TRUE) copy = tempfile(fileext = ".nc") file.copy(input, copy) nc = ncdf4::nc_open(copy, write = TRUE) on.exit({ ncdf4::nc_close(nc); unlink(copy) }, add = TRUE) ncdim_size(nc) })local({ input = system.file("extdata", "temperature_2001_01.nc", package = "nctools", mustWork = TRUE) copy = tempfile(fileext = ".nc") file.copy(input, copy) nc = ncdf4::nc_open(copy, write = TRUE) on.exit({ ncdf4::nc_close(nc); unlink(copy) }, add = TRUE) ncdim_size(nc) })
Modifies the compression setting of one or more variables in an open netCDF object.
ncvar_change_compression(nc, varid = NA, compression)ncvar_change_compression(nc, varid = NA, compression)
nc |
An open netCDF connection created with |
varid |
Variable identifier. This can be a character string giving the
variable name, or an object of class |
compression |
Numeric compression level to assign. |
The modified netCDF object.
local({ input = system.file("extdata", "temperature_2001_01.nc", package = "nctools", mustWork = TRUE) copy = tempfile(fileext = ".nc") file.copy(input, copy) nc = ncdf4::nc_open(copy, write = TRUE) on.exit({ ncdf4::nc_close(nc); unlink(copy) }, add = TRUE) nc = ncvar_change_compression(nc, compression = 4) ncvar_compression(nc) # This changes the in-memory definition, not the stored data. })local({ input = system.file("extdata", "temperature_2001_01.nc", package = "nctools", mustWork = TRUE) copy = tempfile(fileext = ".nc") file.copy(input, copy) nc = ncdf4::nc_open(copy, write = TRUE) on.exit({ ncdf4::nc_close(nc); unlink(copy) }, add = TRUE) nc = ncvar_change_compression(nc, compression = 4) ncvar_compression(nc) # This changes the in-memory definition, not the stored data. })
Returns the compression setting of one variable, or of all variables, in an open netCDF file.
ncvar_compression(nc, varid = NA)ncvar_compression(nc, varid = NA)
nc |
An open netCDF connection created with |
varid |
Variable identifier. This can be a character string giving the
variable name, or an object of class |
If varid is NA, a named vector or list with the compression setting of
each variable. Otherwise, the compression setting of the selected variable.
local({ input = system.file("extdata", "temperature_2001_01.nc", package = "nctools", mustWork = TRUE) copy = tempfile(fileext = ".nc") file.copy(input, copy) nc = ncdf4::nc_open(copy, write = TRUE) on.exit({ ncdf4::nc_close(nc); unlink(copy) }, add = TRUE) ncvar_compression(nc) })local({ input = system.file("extdata", "temperature_2001_01.nc", package = "nctools", mustWork = TRUE) copy = tempfile(fileext = ".nc") file.copy(input, copy) nc = ncdf4::nc_open(copy, write = TRUE) on.exit({ ncdf4::nc_close(nc); unlink(copy) }, add = TRUE) ncvar_compression(nc) })
Returns the dimensions associated with one variable, or with all variables in an open netCDF file.
ncvar_dim(nc, varid = NULL, value = FALSE)ncvar_dim(nc, varid = NULL, value = FALSE)
nc |
An open netCDF connection created with |
varid |
Variable identifier. This can be a character string giving the
variable name, or an object of class |
value |
Logical. If |
If varid is NULL, a named list with one element per variable. If varid
is supplied, the dimensions of the selected variable only. When
value = FALSE, dimensions are returned as character vectors of dimension
names. When value = TRUE, dimensions are returned as named lists of
coordinate values.
ncvar_size(), ncdim_size(), ncdf4::nc_open()
local({ input = system.file("extdata", "temperature_2001_01.nc", package = "nctools", mustWork = TRUE) copy = tempfile(fileext = ".nc") file.copy(input, copy) nc = ncdf4::nc_open(copy, write = TRUE) on.exit({ ncdf4::nc_close(nc); unlink(copy) }, add = TRUE) ncvar_dim(nc) })local({ input = system.file("extdata", "temperature_2001_01.nc", package = "nctools", mustWork = TRUE) copy = tempfile(fileext = ".nc") file.copy(input, copy) nc = ncdf4::nc_open(copy, write = TRUE) on.exit({ ncdf4::nc_close(nc); unlink(copy) }, add = TRUE) ncvar_dim(nc) })
Returns the dimension sizes of a selected variable in an open netCDF file.
ncvar_size(nc, varid = NULL)ncvar_size(nc, varid = NULL)
nc |
An open netCDF connection created with |
varid |
Variable identifier. This can be a character string giving the
variable name, or an object of class |
If the file contains more than one variable, varid must be supplied.
A numeric vector giving the dimension sizes of the selected variable. If the file contains a single variable, that variable is used by default.
local({ input = system.file("extdata", "temperature_2001_01.nc", package = "nctools", mustWork = TRUE) copy = tempfile(fileext = ".nc") file.copy(input, copy) nc = ncdf4::nc_open(copy, write = TRUE) on.exit({ ncdf4::nc_close(nc); unlink(copy) }, add = TRUE) ncvar_size(nc) })local({ input = system.file("extdata", "temperature_2001_01.nc", package = "nctools", mustWork = TRUE) copy = tempfile(fileext = ".nc") file.copy(input, copy) nc = ncdf4::nc_open(copy, write = TRUE) on.exit({ ncdf4::nc_close(nc); unlink(copy) }, add = TRUE) ncvar_size(nc) })
write_ncdf() is an S3 generic for writing R objects to a netCDF file.
Methods are provided for writing a single array-like object
(write_ncdf.default()) and a list of arrays (write_ncdf.list()).
write_ncdf(x, filename, ...) ## Default S3 method: write_ncdf( x, filename, varid, dim, longname, units, prec = "float", missval = NA, compression = 9, chunksizes = NA, verbose = FALSE, dim.names, dim.units, dim.longname, unlim = FALSE, global = list(), force_v4 = FALSE, ... ) ## S3 method for class 'list' write_ncdf( x, filename, varid, dim, longname, units, prec = "float", missval = NA, compression = 9, chunksizes = NA, verbose = FALSE, dim.names, dim.units, dim.longname, unlim = FALSE, global = list(), force_v4 = FALSE, ... )write_ncdf(x, filename, ...) ## Default S3 method: write_ncdf( x, filename, varid, dim, longname, units, prec = "float", missval = NA, compression = 9, chunksizes = NA, verbose = FALSE, dim.names, dim.units, dim.longname, unlim = FALSE, global = list(), force_v4 = FALSE, ... ) ## S3 method for class 'list' write_ncdf( x, filename, varid, dim, longname, units, prec = "float", missval = NA, compression = 9, chunksizes = NA, verbose = FALSE, dim.names, dim.units, dim.longname, unlim = FALSE, global = list(), force_v4 = FALSE, ... )
x |
Object to write. Supported methods currently accept either a single array-like object or a list of array-like objects. |
filename |
Character string giving the path to the netCDF file to create. |
... |
Additional arguments passed to methods. |
varid |
Character string giving the name of the variable to create in the output file. |
dim |
A named or unnamed list defining the coordinates of each
dimension. Each element contains the coordinate values for one dimension.
If omitted, dimensions are generated as |
longname |
Character string giving the long name of the output variable.
Defaults to |
units |
Character string giving the units of the output variable.
Defaults to |
prec |
Character string giving the storage precision passed to
|
missval |
Missing value used in the netCDF variable definition. |
compression |
Numeric compression level passed to
|
chunksizes |
Optional chunk sizes for compressed variables. |
verbose |
Logical. Should |
dim.names |
Character vector with names for the dimensions when |
dim.units |
Character vector giving the units of the dimensions. If omitted, empty strings are used. |
dim.longname |
Character vector giving the long names of the dimensions. If omitted, empty strings are used. |
unlim |
Character string naming the unlimited dimension. Use |
global |
Named list of global attributes to add to the output file.
A |
force_v4 |
Logical. Should the output file be forced to netCDF4 format? |
write_ncdf.default() writes a single object x as one variable in a new
netCDF file. The dimensions of the variable are defined by dim.
If dim is unnamed, dimension names are taken from dim.names, or generated
automatically as "dim1", "dim2", and so on. Dimension units and long
names can be supplied through dim.units and dim.longname.
write_ncdf.list() writes each element of x as a separate variable in the
same netCDF file.
If varid is omitted, variable names are taken from names(x). Arguments
such as longname, units, and prec can be supplied either as length-one
values, to be recycled to all variables, or as one value per variable.
The object dim defines the full set of dimensions available in the file.
Individual variables may use all or a subset of those dimensions, provided
their sizes are consistent with the declared dimension lengths.
Invisibly returns filename.
local({ # Synthetic daily temperature for January 2001, as in the bundled data lon = seq(-80, -65, length.out = 15) lat = seq(-25, -6, length.out = 20) days = 0:30 spatial = outer(lon, lat, function(x, y) 16 + 6 * exp(-((x + 72)^2 / 16 + (y + 15)^2 / 36)) - 0.15 * (y + 15)) temperature = outer(spatial, days, function(field, day) field + 2 * sin(2 * pi * day / 365) + 0.2 * sin(2 * pi * day / 7)) temperature[1:2, 1:2, ] = NA_real_ files = vapply(seq_len(3), function(i) tempfile(fileext = ".nc"), "") on.exit(unlink(files)) # Quick defaults: dimensions are named dim1, dim2, dim3, with index values write_ncdf(temperature, filename = files[1], varid = "temperature") # Supply geographic coordinates, time coordinates, and variable metadata coordinates = list(lon = lon, lat = lat, time = days) coordinate_units = c("degrees_east", "degrees_north", "days since 2001-01-01") write_ncdf(temperature, filename = files[2], varid = "temperature", dim = coordinates, dim.units = coordinate_units, longname = "Synthetic daily temperature", units = "degree_C") # Add descriptive attributes, unlimited time, and explicit storage settings write_ncdf(temperature, filename = files[3], varid = "temperature", dim = coordinates, dim.units = coordinate_units, dim.longname = c("Longitude", "Latitude", "Time"), longname = "Synthetic daily temperature", units = "degree_C", unlim = "time", prec = "float", missval = -9999, compression = 4, force_v4 = TRUE, global = list( title = "Synthetic temperature for January 2001", source = "Spatial gradient and Gaussian centre with annual and weekly cycles", comment = "Synthetic data, not observations; a fixed corner patch is missing." )) nc = ncdf4::nc_open(files[3]) tryCatch({ print(ncvar_dim(nc, "temperature")) print(ncdf4::ncatt_get(nc, 0, "title")) }, finally = ncdf4::nc_close(nc)) })local({ # Synthetic daily temperature for January 2001, as in the bundled data lon = seq(-80, -65, length.out = 15) lat = seq(-25, -6, length.out = 20) days = 0:30 spatial = outer(lon, lat, function(x, y) 16 + 6 * exp(-((x + 72)^2 / 16 + (y + 15)^2 / 36)) - 0.15 * (y + 15)) temperature = outer(spatial, days, function(field, day) field + 2 * sin(2 * pi * day / 365) + 0.2 * sin(2 * pi * day / 7)) temperature[1:2, 1:2, ] = NA_real_ files = vapply(seq_len(3), function(i) tempfile(fileext = ".nc"), "") on.exit(unlink(files)) # Quick defaults: dimensions are named dim1, dim2, dim3, with index values write_ncdf(temperature, filename = files[1], varid = "temperature") # Supply geographic coordinates, time coordinates, and variable metadata coordinates = list(lon = lon, lat = lat, time = days) coordinate_units = c("degrees_east", "degrees_north", "days since 2001-01-01") write_ncdf(temperature, filename = files[2], varid = "temperature", dim = coordinates, dim.units = coordinate_units, longname = "Synthetic daily temperature", units = "degree_C") # Add descriptive attributes, unlimited time, and explicit storage settings write_ncdf(temperature, filename = files[3], varid = "temperature", dim = coordinates, dim.units = coordinate_units, dim.longname = c("Longitude", "Latitude", "Time"), longname = "Synthetic daily temperature", units = "degree_C", unlim = "time", prec = "float", missval = -9999, compression = 4, force_v4 = TRUE, global = list( title = "Synthetic temperature for January 2001", source = "Spatial gradient and Gaussian centre with annual and weekly cycles", comment = "Synthetic data, not observations; a fixed corner patch is missing." )) nc = ncdf4::nc_open(files[3]) tryCatch({ print(ncvar_dim(nc, "temperature")) print(ncdf4::ncatt_get(nc, 0, "title")) }, finally = ncdf4::nc_close(nc)) })