Skip to contents

Resamples x onto the CRS, extent, resolution, and origin of ref. By default the resampling method is chosen from the resolution ratio and whether x is categorical, and reported on the console; pass method to override.

Usage

resample_to_grid(x, ref = ab_grid(), method = "auto", quiet = FALSE, ...)

Arguments

x

A SpatRaster to align.

ref

A SpatRaster used as the target grid. Defaults to the ABMI 1 km Alberta grid, ab_grid().

method

Character; resampling method passed to terra::resample(). "auto" (the default) selects one as described above. Any value terra::resample() accepts may be given instead: "near", "bilinear", "cubic", "cubicspline", "lanczos", "average", "sum", "mode", "min", "q1", "median", "q3", "max", or "rms".

quiet

Logical; if TRUE, suppress the message reporting the method used. Default FALSE.

...

Additional arguments passed to terra::resample().

Value

A SpatRaster with the same CRS, extent, resolution, and origin as ref.

Details

terra::resample() always returns a layer on ref's geometry. The method argument decides only what value each output cell takes, and the appropriate choice depends on the direction of the resolution change:

DirectionContinuousCategorical
Coarsening (fine to coarse)"average""mode"
Same resolution"near""near"
Refining (coarse to fine)"bilinear""near"

Coarsening is the case worth care. Going from 30 m to 1 km each output cell covers roughly 1,111 input cells; "average" summarises all of them, whereas "bilinear" blends four and "near" takes one. At equal resolution there is nothing to summarise, and "near" moves values to the nearest cell without the variance loss interpolation would cause.

"auto" treats x as categorical when terra::is.factor(x)[1] is TRUE. A layer holding class codes as plain numbers is not detectable as categorical, so pass method = "mode" or method = "near" for those.

This function does not reproject. A CRS mismatch between x and ref is an error, because terra::resample() handed a layer in another CRS returns a raster of NA rather than failing. Reproject first with terra::project().

See also

check_alignment() to confirm the result; terra::aggregate() for summaries terra::resample() does not provide, such as sd or a custom function.

Examples

if (FALSE) { # \dontrun{
library(terra)

# Coarsening: chooses "average"
fine <- rast(res = 30, crs = "EPSG:3400",
             xmin = 0, xmax = 9000, ymin = 0, ymax = 9000)
fine[] <- runif(ncell(fine))
ref <- rast(res = 1000, crs = "EPSG:3400",
            xmin = 0, xmax = 9000, ymin = 0, ymax = 9000)
out <- resample_to_grid(fine, ref)

# Override when the default is not what you want
totals <- resample_to_grid(fine, ref, method = "sum")

# Onto the default ABMI 1 km Alberta grid
out2 <- resample_to_grid(fine)
} # }