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

问题描述 投票:1回答:2

我有一个数据框table,我想计算我的数据帧的每个可能的列对mahalanobis。

           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列所以如果有人知道怎么做:)谢谢

r lapply do.call mahalanobis
2个回答
0
投票

函数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

0
投票

马哈拉诺比斯计算如下:

enter image description here

我想做Mahalanobis距离的想法如下:

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

© www.soinside.com 2019 - 2024. All rights reserved.