```
library(magrittr)
library(StatMatch)
## Mahalanobis distance between two observations (row vectors) within a dataset
(md1 <- mahalanobis.dist(iris[1:6,1:4]))
## 1 2 3 4 5 6
## 1 0.000000 2.237463 2.931554 2.931554 1.216908 2.781191
## 2 2.237463 0.000000 2.983245 2.983245 3.087399 3.076939
## 3 2.931554 2.983245 0.000000 3.162278 2.645122 3.146122
## 4 2.931554 2.983245 3.162278 0.000000 2.645122 3.146122
## 5 1.216908 3.087399 2.645122 2.645122 0.000000 2.828648
## 6 2.781191 3.076939 3.146122 3.146122 2.828648 0.000000
## Mean Mahalanobis distance (only take upper triangle to avoid redundancy)
mean(md1[upper.tri(md1, diag = FALSE)])
## [1] 2.786861
## Mahalanobis distance across observations of two datasets
(md2 <- mahalanobis.dist(data.x = iris[1:6,1:4], data.y=iris[51:60, 1:4]))
## 51 52 53 54 55 56 57 58 59 60
## 1 2.436196 2.365736 2.403783 3.043400 2.642437 3.754365 2.923451 2.805929 2.647285 3.311052
## 2 2.800444 3.092379 2.812487 2.235670 2.336177 4.413751 3.939878 2.483022 2.787769 3.589561
## 3 2.849757 2.522174 2.728452 2.451016 2.566549 3.731635 3.085493 2.132844 2.846456 2.862299
## 4 3.108617 3.066840 2.916643 2.936469 3.307360 2.697649 3.318866 2.005847 2.563267 3.310547
## 5 2.750774 2.421374 2.636453 3.444474 3.139134 3.319354 2.646488 2.900933 2.836002 3.259673
## 6 3.002521 2.092075 2.928283 3.939695 3.197274 4.282992 2.272397 3.739204 3.632813 3.226292
## Mean Mahalanobis distance
mean(md2)
## [1] 2.958363