Learn R Programming

terra (version 1.8-86)

writeCDF: Write raster data to a NetCDF file

Description

Write a SpatRaster or SpatRasterDataset to a NetCDF file.

When using a SpatRasterDataset, the varname, longname, and unit should be set in the object (see examples).

Always use the ".nc" or ".cdf" file extension to assure that the file can be properly read again by GDAL

You can write multiple rasters (variables) that are two (x, y), three (x, y, z or x, y, time) or four dimensional (x, y, z, time).

See depth and time for specifying the axes of the thrid and/or fourth dimension(s).

Usage

# S4 method for SpatRaster
writeCDF(x, filename, varname, longname="", unit="", split=FALSE, ...)

# S4 method for SpatRasterDataset writeCDF(x, filename, overwrite=FALSE, timename="time", atts="", gridmap="", prec="float", compression=NA, missval, tags=FALSE, ...)

Arguments

Value

SpatRaster or SpatDataSet

See Also

see writeRaster for writing other file formats

Examples

Run this code

f <- system.file("ex/elev.tif", package="terra")
r <- rast(f)
fname <- paste0(tempfile(), ".nc")
rr <- writeCDF(r, fname, overwrite=TRUE, varname="alt", 
      longname="elevation in m above sea level", unit="m")

a <- rast(ncols=5, nrows=5, nl=50)
values(a) <- 1:prod(dim(a))
time(a) <- as.Date("2020-12-31") + 1:nlyr(a)
aa <- writeCDF(a, fname, overwrite=TRUE, varname="power", 
      longname="my nice data", unit="U/Pa")

b <- sqrt(a)
s <- sds(a, b)
names(s) <- c("temp", "prec")
longnames(s) <- c("temperature (C)", "precipitation (mm)")
units(s) <- c("°C", "mm")
ss <- writeCDF(s, fname, overwrite=TRUE)

# four dimensional 
r1 <- rast(nrow=5, ncol=5, vals=1:100, nlyr=4)
depth(r1) <- c(0, 2, 0, 2)
time(r1) <- c(as.Date("2012-12-12") + c(1,1,2,2))
depthName(r1) <- "angle"

r2 <- rast(nrow=5, ncol=5, vals=1:150, nlyr=6)
depth(r2) <- c(10, 10, 20, 20, 30, 30)
time(r2) <- c(as.Date("2012-12-12") + c(1:2, 1:2, 1:2))
depthName(r2) <- "height"
depthUnit(r2) <- "cm"

s <- sds(r1, r2)
names(s) <- c("TH", "DBZH")
units(s) <- c("-", "Pa")
x <- writeCDF(s, filename = fname, overwrite=TRUE)
x[1]
time(x[1])
depth(x[1])

x[2]
time(x[2])
depth(x[2])

# for CRAN
file.remove(fname)

Run the code above in your browser using DataLab