Mahalanobis distance of each pair of observations

馋奶兔 提交于 2019-12-06 04:31:58

You need some mathematical knowledge.

  1. Do a Cholesky factorization of empirical covariance, then standardize your observations;
  2. use dist to compute Euclidean distance on transformed observations.

dist.maha <- function (dat) {
  X <- as.matrix(na.omit(dat))  ## ensure a valid matrix
  V <- cov(X)  ## empirical covariance; positive definite
  L <- t(chol(V))  ## lower triangular factor
  stdX <- t(forwardsolve(L, t(X)))  ## standardization
  dist(stdX)  ## use `dist`
  }

Example

set.seed(0)
x <- matrix(rnorm(6 * 3), 6, 3)

dist.maha(x)
#         1        2        3        4        5
#2 2.362109                                    
#3 1.725084 1.495655                           
#4 2.959946 2.715641 2.690788                  
#5 3.044610 1.218184 1.531026 2.717390         
#6 2.740958 1.694767 2.877993 2.978265 2.794879

The result agrees with your mhbd_calc2.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!