Last data update: 2014.03.03

R: A function for transforming a matrix from its Euclidean space...
e2mR Documentation

A function for transforming a matrix from its Euclidean space to its Mahalanobis space

Description

A function for transforming a matrix from its Euclidean space to its Mahalanobis space

Usage

e2m(X, sm.method = c("svd", "eigen"))

Examples

# test data
## Not run: 
X <- matrix(rnorm(500),ncol=5)
# Normal way to compute the Mahalanobis distance
md1 <- sqrt(mahalanobis(X, center = colMeans(X), cov = cov(X)))
# Projection approach for computing the Mahalanobis distance
#1. Projecting from the Euclidean to the Mahalanobis space
Xm <- e2m(X, sm.method = 'svd')
#2. Use the normal Euclidean distance on the Mahalanobis space
md2 <- sqrt(rowSums((sweep(Xm, 2, colMeans(Xm), '-'))^2))
# Plot the results of both methods
plot(md1, md2)
# Test on a real dataset
#Mahalanobis in the spectral space
data(NIRsoil)
X <- NIRsoil$spc
Xm <- e2m(X, sm.method = 'svd')
md2 <- sqrt(rowSums((sweep(Xm, 2, colMeans(Xm), '-'))^2))

md1 <- sqrt(mahalanobis(X, center = colMeans(X), cov = cov(X))) # does not work#'
#Mahalanobis in the PC space
pc <- 20
pca <- prcomp(X, center=TRUE,scale=TRUE)
X <- pca$x[, 1:pc]
X2 <- sweep(pca$x[,1:pc,drop=FALSE],2,pca$sdev[1:pc],'/')
md4 <- sqrt(rowSums((sweep(Xm, 2, colMeans(Xm), '-'))^2))
md5 <- sqrt(rowSums((sweep(X2, 2, colMeans(X2), '-'))^2))
md3 <- sqrt(mahalanobis(X, center = colMeans(X), cov = cov(X))) # does work

## End(Not run)

Results