
Transform Environmental Data for Global Mahalanobis Distance
Source:R/mahalanobis_transform.R
mahalanobis_transform.RdTransforms environmental data to decorrelated, unit-variance space, enabling the use of Euclidean distance as a global Mahalanobis distance. Useful for climate analog analysis when you want to account for spatial correlation structure and/or standardize variables with different units.
Arguments
- x
Climate data for focal/query points. Can be:
Matrix/data.frame with columns x, y, and environmental variables
SpatRaster with environmental variable layers
- pool
Optional reference environmental data to transform jointly with
x. When provided, both datasets are transformed using the same transformation (computed from their combined covariance structure). Must have the same number of environmental variables asx. Same format options asx.- center
Either a logical value or a numeric vector of per-variable centers, as in
base::scale().TRUE(default) centers each variable on its mean in the combined data;FALSEapplies no centering; a numeric vector (one value per environmental variable, in original units) is used as supplied.- scale
Either a logical value or a numeric vector of per-variable standard deviations, as in
base::scale().TRUE(default) standardizes each variable to unit variance before whitening (correlation-based);FALSEwhitens the raw covariance; a numeric vector (positive, one per variable, in original units) is used as supplied. Pairwise distances are the same either way;scaleonly changes the orientation of the whitened axes.- cov
Optional covariance matrix of the environmental variables, in their original units (
n_envxn_env, symmetric positive definite).NULL(default) estimates it from the combined data.
Value
If pool = NULL: Returns transformed version of x in the same
format (matrix/data.frame/SpatRaster).
If pool is provided: Returns a list with two components:
$x: Transformed version ofx$pool: Transformed version ofpool
Both use the same format as their respective inputs. Output variables
inherit input names with a _transformed suffix (e.g. tmean
becomes tmean_transformed); each transformed axis is the whitened
counterpart of its corresponding input variable.
Each returned object carries an attribute "mahalanobis": a list with the
center, scale and cov (original units) that defined the transform.
Pass these back as arguments to apply the identical transform to other
data, e.g. future climate or a different spatial subset.
Rows / cells with NA values in any coordinate or environmental column are excluded from the covariance estimation but preserved as NA in the returned output, so the result has the same shape (row count / cell count) as the input.
Details
The transformation uses eigendecomposition of the covariance (or correlation) matrix to decorrelate variables and scale to unit variance in all directions. After transformation, Euclidean distance in the transformed space is equivalent to Mahalanobis distance in the original space.
The transformation is: X_transformed = (X - μ) %*% Σ^(-1/2), computed via symmetric (ZCA / Mahalanobis) whitening: \(\Sigma^{-1/2} = V D^{-1/2} V'\). This is the unique whitening that keeps the transformed axes as close as possible (in least-squares sense) to the original variables, so each output column corresponds one-to-one with its input counterpart. PCA whitening would give identical pairwise distances but reorient the axes to principal components.
When pool is provided, any estimated center, scale or covariance is
computed from the combined dataset so both are transformed to the same
space. Supplying all three fixes the transform, so separate calls (e.g.
historical vs. future climate) share one metric.
If the covariance matrix is near-singular, a small regularization term (1e-6 * max eigenvalue) is added to stabilize the inversion.
Examples
if (FALSE) { # \dontrun{
# Single dataset transformation
env_transformed <- mahalanobis_transform(climate_data)
# Joint transformation for analog analysis
transformed <- mahalanobis_transform(
x = baseline_climate,
pool = future_climate
)
# Use transformed data with Euclidean distance (= global Mahalanobis)
analogs <- analog_search(
x = transformed$x,
pool = transformed$pool,
select = "knn_geog",
env = kernel(max = 2), # Now in standardized units
k = 1
)
# Reuse a fitted transform on other data
hist <- mahalanobis_transform(baseline_climate)
p <- attr(hist, "mahalanobis")
fut <- mahalanobis_transform(future_climate, center = p$center,
scale = p$scale, cov = p$cov)
# Covariance-based transformation (preserve relative variances)
transformed_cov <- mahalanobis_transform(
x = climate_data,
scale = FALSE
)
} # }