函数 mahalanobis 返回平方的 Mahalanobis 距离,然后您可以执行以下操作:
table <- iris[1:10, -5]
coln <- combn(colnames(table), 2)
out <- apply(coln, 2, function(x) sqrt(mahalanobis(table[, x], colMeans(table[, x]), cov(table[, x]))))
colnames(out) <- apply(coln, 2, paste, collapse = "_")
out
Sepal.Length_Sepal.Width Sepal.Length_Petal.Length Sepal.Length_Petal.Width Sepal.Width_Petal.Length Sepal.Width_Petal.Width
1 0.6808740 2.1111068 1.0495913 1.2242322 1.2236349
2 3.3019215 0.4836711 0.1275204 1.0238329 1.3640406
3 0.3160289 2.0549883 0.3040872 2.1087531 0.1284711
4 0.7972596 2.3548714 0.8043597 1.3831695 0.5496880
5 1.0730825 1.1132502 0.4512262 2.1350123 2.3749610
6 3.9962218 5.6939205 6.3564033 6.0656020 5.4638846
7 3.4022539 0.8045986 2.9231608 0.6036855 1.3184087
8 0.2499919 0.2784879 0.4512262 0.2180897 0.4654446
9 2.5149505 2.8599376 2.6288828 1.8544533 2.5715289
10 1.6674153 0.2451676 2.9035422 1.3831695 2.5399376
Petal.Length_Petal.Width
1 0.2144860
2 0.2144860
3 2.2331776
4 0.5509346
5 0.2144860
6 6.9434579
7 2.3803738
8 0.5509346
9 0.2144860
10 4.4831776