R中数据框中一对列的马哈拉诺比斯距离

mahalanobis distance for pair of columns in data frame in R

我有一个数据框 table,我想为我的数据框的每一对可能的列计算马哈拉诺比斯。

           A1        A2          A3
     121.4984  219.5448    250.7575
     121.5195  219.5451    250.7500
     121.5089  219.4667    250.5645
     121.5510  219.6235    250.5645
     121.8034  219.4235    250.0005 

我想计算 A1A2A1A3A2A3 之间的距离 .. . 我可能有多达 50 列,所以如果有人知道如何做:) 谢谢

函数mahalanobis return平方马氏距离,那么你可以这样做:

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

马氏计算为:

我做马氏距离的想法如下:

Mahalanob <- function(data){
  CovMat <- cov(data)
  S <- apply(data, 2, FUN = function(x) { x - mean(x) })
  dmahal <- S %*% solve(as.matrix(CovMat)) %*% t(S)
  return(dmahal)
}

如果要指定数据集,可以包含一个 y 变量并更改 x-mean(x) x-y