svkucheryavski / mdatools

R package for Multivariate Data Analysis
https://mda.tools
Other
33 stars 11 forks source link

Number of point inside Hotelling ellipse. #92

Closed mashranga closed 4 years ago

mashranga commented 4 years ago

Is it possible to count the number of points inside/outside of the Hotelling ellipse? Thanks a lot .

svkucheryavski commented 4 years ago

Well, this is not implemented in mdatools but you can write a simple code that does it. See example below.

# set confidence limit
conf.lim <- 0.95

# generate random data
nrows <- 100
ncols <- 10
set.seed(42)
data <- matrix(rnorm(nrows * ncols), nrows, ncols)

# do PCA and make scores plot for calibration set
library(mdatools)
m <- pca(data, 5)
p <- plotScores(m$calres)

# add the Hotelling ellipse
plotHotellingEllipse(p, conf.lim = conf.lim)

# get score values from the plot
t1 <- as.numeric(p$x_values)
t2 <- as.numeric(p$y_values)

# find critical limit for Hotelling ellipse
nobj <- length(t1)
T2lim <- (2 * (nobj - 1) / (nobj - 2)) * qf(conf.lim, 2, (nobj - 2))

# find points outside the limits
s1 <- sd(t1)^2
s2 <- sd(t2)^2
ind <- which(t1^2/s1 + t2^2/s2 > T2lim)

# show number of points
show(length(ind))

# show points as red circles on the plot
points(t1[ind], t2[ind], col = "red", pch = 1, cex = 2)
mashranga commented 4 years ago

Thanks for a very quick response.

svkucheryavski commented 4 years ago

You are welcome. If it solves the problem, I will close the issue.