Learn R Programming

fit.models (version 0.5-13)

mahalanobis: Mahalanobis Distance

Description

Returns the squared Mahalanobis distance of all rows in x and the vector \(\mu\) = center with respect to \(\Sigma\) = cov. This is (for vector x) defined as $$D^2 = (x - \mu)' \Sigma^{-1} (x - \mu).$$ The fit.models package makes the mahalanobis function generic. The default method calls the mahalanobis function in the stats package. Methods for fitted model objects return the squared Mahalanobis distance of all the rows in the design (model) matrix.

Usage

mahalanobis(x, ...)

# S3 method for default mahalanobis(x, center, cov, inverted = FALSE, ...)

# S3 method for lm mahalanobis(x, ...)

Arguments

x
a vector or matrix of data with, say, p columns. If x is a fitted model object then the design matrix (model matrix) is used.
passed to solve for computing the inverse of the covariance matrix (if inverted is FALSE). Additional arguments are ignored when x is a fitted model object.
center
mean vector of the distribution or second data vector of length p or recyclable to that length. If set to FALSE, the centering step is skipped. This argument is ignored when x is a fitted model object.
cov
covariance matrix (p x p) of the distribution. This argument is ignored when x is a fitted model object.
inverted
logical. If TRUE, cov is supposed to contain the inverse of the covariance matrix. This argument is ignored when x is a fitted model object.

Value

a numeric vector containing the squared Mahalanobis distances

Methods (by class)

  • default: the default S3 method calls stats::mahalanobis
  • lm: the method for lm objects returns the squared mahalanobis distance for each row in the design (model) matrix. These values are computed from the diagonal elements of the hat matrix.

Examples

Run this code
stack.lm <- lm(stack.loss ~ ., data = stackloss)

# Mahalanobis distance (not squared)
sqrt(mahalanobis(stack.lm))

Run the code above in your browser using DataLab