Applies a focal operation to a SpatRaster
using either a 'C++' backend
(via terra) or an 'FFT' backend. Window types include rectangle, circle,
gaussian, pareto, idw, exponential, triangular, cosine, logistic, cauchy,
quartic, epanechnikov, or you may pass a numeric matrix as the kernel.
Arguments
- x
SpatRaster. Input raster (1+ layers).
- d
numeric. Radius/size in map units (ignored if
w
is a matrix).- w
character or numeric matrix. Window type, or a custom kernel matrix.
- fun
character. One of "mean","sum","min","max","sd","median".
- engine
character. "auto" (default), "cpp", or "fft".
- na.rm
logical. Remove NAs before applying the summary function.
- na.policy
character. "omit" (default) leaves NA centers as NA; "all" fills centers when neighbors exist (FFT path respects this; C++ path emulates center handling after the call).
- pad
character. "none" or "auto" (pad to next 5-smooth sizes for FFT).
- ...
Extra args to
terra::focal()
for the 'C++' path.
Value
terra::SpatRaster with the same geometry as x
.
Details
The 'FFT' backend uses masked convolution with proper NA semantics and can
pad to "5-smooth" sizes for stable speed. With engine = "auto"
, the function
chooses between 'C++' and 'FFT' based on a simple window-size heuristic.
Examples
set.seed(1)
r <- terra::rast(nrows = 12, ncols = 12, xmin = 0, xmax = 12, ymin = 0, ymax = 12)
terra::values(r) <- stats::runif(terra::ncell(r))
# Mean with a small circular window (d is in map units; here res = 1)
m_circ <- fastfocal(r, d = 2, w = "circle", fun = "mean")
# Same idea using a custom 3x3 box kernel (uniform mean)
k3 <- matrix(1, 3, 3)
m_box <- fastfocal(r, w = k3, fun = "mean")
# Tiny numeric summaries (keeps examples fast & quiet for CRAN)
as.numeric(terra::global(m_circ, "mean", na.rm = TRUE))
#> [1] 0.5117419
as.numeric(terra::global(m_box, "mean", na.rm = TRUE))
#> [1] 0.5094344