我在程序包StatMatch(http://cran.r-project.org/web/packages/StatMatch/StatMatch.pdf)中找到了mahalanobis.dist函数,但它并没有完全符合我的要求.它似乎是计算数据中每次观察的马哈拉诺比斯距离.对于data.x中的每次观察
我想计算data.y中一个观测值的mahalanobis距离到data.x中的所有观测值.如果有意义的话,基本上计算一个点的马哈拉诺比斯距离到点的"云".有点想到观察成为另一组观察的一部分的概念
这个人(http://people.revoledu.com/kardi/tutorial/Similarity/MahalanobisDistance.html)似乎正在这样做,我试图在R中复制他的过程但是当我到达底部时它失败了等式:
mahaldist = sqrt((inversepooledcov %*% t(meandiffmatrix)) %*% meandiffmatrix)
Run Code Online (Sandbox Code Playgroud)
我正在使用的所有代码都在这里:
a = rbind(c(2,2), c(2,5), c(6,5),c(7,3))
colnames(a) = c('x', 'y')
b = rbind(c(6,5),c(3,4))
colnames(b) = c('x', 'y')
acov = cov(a)
bcov = cov(b)
meandiff1 = mean(a[,1]) - mean(b[,1])
meandiff2 = mean(a[,2]) - mean(b[,2])
meandiffmatrix = rbind(c(meandiff1,meandiff2))
totaldata = dim(a)[1] + dim(b)[1]
pooledcov = (dim(a)[1]/totaldata * acov) + (dim(b)[1]/totaldata * bcov)
inversepooledcov = solve(pooledcov)
mahaldist = sqrt((inversepooledcov %*% t(meandiffmatrix)) %*% meandiffmatrix)
Run Code Online (Sandbox Code Playgroud)