mahalanobis
Mahalanobis Distance

Description

Returns a vector of the Mahalanobis distances for the rows of a data matrix.

Usage

mahalanobis(x, center, cov, inverted = FALSE, ...)

Arguments

x vector or matrix of data. Rows represent observations and columns represent variables. Missing values (NAs) are allowed.
center a numeric vector, center should not be longer than the number of column of x, usually is the mean of the distribution. Missing values (NAs) are allowed.
cov matrix giving the covariance matrix for the distribution. This must be square and have the same number of columns as x. This may alternatively be a QR decomposition of the covariance matrix, or the inverse of the covariance matrix (see inverted). Missing values (NAs) are not allowed.
inverted logical flag to specify if cov has been inverted. If FALSE, cov will be inverted before it is used.
... other arguments to pass in or from other functions.

Details

The result contains missing values (NAs) for rows of x that contain missing values. The ith element of the result is equal to t(x[i,]-center) %*% invcov %*% (x[i,]-center) where invcov is the inverse of cov.
Value
a numeric vector, each element of which is the (squared) Mahalanobis distance for the corresponding row of x.
References
The Mahalanobis distance is discussed in many multivariate books such as:
Mardia, K. V., Kent, J. T. and Bibby, J. M. (1979). Multivariate Analysis. Academic Press, London.
See Also
dist, qr.
Examples
y <- cbind(c(2,3,4,1,7,6), c(2,3,5))
vy <- var(y)
mahalanobis(c(0,0), 1:2, cov=vy)
# [1] 2.428571

x <- matrix(rnorm(3*13), ncol=3) mx <- colMeans(x) vx <- var(x) m1 <- mahalanobis(x, mx, vx)

qrv <- qr(vx) m2 <- mahalanobis(x, mx, qrv)

vinv <- solve(qrv) m3 <- mahalanobis(x, mx, vinv, inverted=TRUE) # m1, m2 and m3 are the same

Package stats version 6.1.1-7
Package Index