Skip to Main Content

How to compute Mahalanobis distance? | SAS FAQ

The relationship between Mahalanobis distance and hat matrix diagonal is as
follows.

hii = [((MDi)2)/(N-1)] + [1/N].

Based on this formula, it is fairly straightforward to compute Mahalanobis distance after regression. Here is an example using
the stackloss data set.

data stackloss;
input x1 x2 x3 y;
datalines;
  80  27  89  42
  80  27  88  37
  75  25  90  37
  62  24  87  28
  62  22  87  18
  62  23  87  18
  62  24  93  19
  62  24  93  20
  58  23  87  15
  58  18  80  14
  58  18  89  14
  58  17  88  13
  58  18  82  11
  58  19  93  12
  50  18  89   8
  50  18  86   7
  50  19  72   8
  50  19  79   8
  50  20  80   9
  56  20  82  15
  70  20  91  15
;
run;
proc reg data = stackloss;
  model y = x1-x3 /influence;
  ods output  OutputStatistics = hat;
run;
quit;
data mahal;
  set hat;
  mahalanobis = sqrt((hatdiagonal-1/21)*20);
run;
proc print data = mahal;
var mahalanobis;
run;