I have two groups, that each group has 3 variables such as following:
Group1:
cost time quality
[1,] 90 4 70
[2,] 4 27 37
[3,] 82 4 17
[4,] 18 41 4
Group2:
cost time quality
[1,] 4 27 4
codes to calculate mahalanobis distance between two groups are as following:
benchmark<-rbind(c(90,4,70),c(4,27,37),c(82,4,17),c(18,41,4))
colnames(benchmark)=c('cost','time','quality')
current=rbind(c(4,27,4))
colnames(current)=c('cost','time','quality')
bdm<-as.matrix(benchmark)
cdm<-as.matrix(current)
mat1<-matrix(bdm,ncol=ncol(bdm),dimnames=NULL)
mat2<-matrix(cdm,ncol=ncol(cdm),dimnames=NULL)
#center Data
mat1.1<-scale(mat1,center = T,scale = F)
mat2.1<-scale(mat2,center=T,scale=F)
#cov Matrix
mat1.2<-cov(mat1.1,method="pearson")
mat2.2<-cov(mat2.1,method="pearson")
#the pooled covariance is calculated using weighted average
n1<-nrow(mat1)
n2<-nrow(mat2)
n3<-n1+n2
#pooled matrix
#pooled matrix
mat3<-((n1/n3)*mat1.2) + ((n2/n3)*mat2.2)
mat4<-solve(mat3)
#Mean diff
mat5<-as.matrix((colMeans(mat1)-colMeans(mat2)))
#multiply
mat6<-t(mat5)%*%mat4
#Mahalanobis distance
sqrt(mat6 %*% mat5)
The Result is NA but when I entered the values in the following link calculate mahalanobis distance to calculate the mahalanobis distance it shows Mahalanobis Distance between group1 and group2 = 2.4642
Moreover the error message that I got is :
Error in ((n1/n3) * mat1.2) + ((n2/n3) * mat2.2) : non-conformable arrays
and the Warning message:
In colMeans(mat1) - colMeans(mat2) :
longer object length is not a multiple of shorter object length