To calculate mahalanobis distance in R, you can use mahalanobis() function from stats package. The Mahalanobis distance is the distance between two points in a multivariate space.

The following method shows how you can do it with syntax.

Method: Use mahalanobis() Function

mahalanobis(df, colMeans(df), cov(df))

colMeans(df): Mean vector cov(df): Covariance matrix

The following example shows how to calculate mahalanobis distance in R.

Use mahalanobis() to Calculate Mahalanobis Distance

Let’s see how to calculate mahalanobis distance of data frame:

# Create data frame
df <- data.frame(Pressure=c(12.39,11.25,12.15,13.48,13.78,12.89,12.21,12.58),
                 Temperature=c(78,89,85,84,81,79,77,85),
                 Humidity=c(5,7,1,2,7,8,9,4))

# Calculate Mahalanobis distance
d <-mahalanobis(df, colMeans(df), cov(df))

# Print Mahalanobis distance
print(d)

Output:

[1] 2.3926589 5.3373797 3.0391869 2.4798019 3.3534422 1.1056642 2.7845952 0.5072711

Here the output shows mahalanobis distance of data frame.