获取由 R 中的汽车包生成的数据椭圆的参数

Getting the parameters of a data ellipse produced by the car package in R

我正在使用 R 中汽车包中的 dataEllipse 函数为我的数据获取椭圆置信区域。例如:

datapoints_x = c(1,3,5,7,8,6,5,4,9)
datapoints_y = c(3,6,8,9,5,8,7,4,8)
ellipse = dataEllipse(cbind(datapoints_x, datapoints_y), levels=0.95)

输出是两个向量 x 和 y,对应于定义椭圆的点:

head(ellipse)
#             x        y
# [1,] 12.79906 10.27685
# [2,] 12.74248 10.84304
# [3,] 12.57358 11.34255
# [4,] 12.29492 11.76781
# [5,] 11.91073 12.11238
# [6,] 11.42684 12.37102

但我更感兴趣的是省略号轴的长度及其中心。有没有办法不自己做PCA就搞定?

?dataEllipse 你读到这些函数主要是绘图函数,而不是旨在为你提供拟合椭圆的函数。但是阅读 dataEllipse 的源代码后,很明显用于拟合椭圆的函数是 stats 包中的 cov.wt。这个函数应该可以给你指定椭圆位置和形状的中心和协方差矩阵:

set.seed(144)
x <- rnorm(1000)
y <- 3*x + rnorm(1000)
(ell.info <- cov.wt(cbind(x, y)))
# $cov
#          x         y
# x 1.022985  3.142274
# y 3.142274 10.705215
# 
# $center
#           x           y 
# -0.09479274 -0.23889445 
# 
# $n.obs
# [1] 1000

现在可以从 ell.info$center 轻松获得椭圆的中心。轴的方向可作为协方差矩阵的特征向量访问(下面 eigen.info$vectors 的列)。

(eigen.info <- eigen(ell.info$cov))
# $values
# [1] 11.63560593  0.09259443
# 
# $vectors
#           [,1]       [,2]
# [1,] 0.2839051 -0.9588524
# [2,] 0.9588524  0.2839051

最后你需要知道轴的长度(我将给出从中心到椭圆的长度,也就是该轴上的半径):

(lengths <- sqrt(eigen.info$values * 2 * qf(.95, 2, length(x)-1)))
# [1] 8.3620448 0.7459512

现在我们可以得到椭圆轴的四个端点:

ell.info$center + lengths[1] * eigen.info$vectors[,1]
#        x        y 
# 2.279234 7.779072 
ell.info$center - lengths[1] * eigen.info$vectors[,1]
#         x         y 
# -2.468820 -8.256861 
ell.info$center + lengths[2] * eigen.info$vectors[,2]
#           x           y 
# -0.81004983 -0.02711513 
ell.info$center - lengths[2] * eigen.info$vectors[,2]
#          x          y 
#  0.6204643 -0.4506738 

我们可以通过使用 dataEllipse:

来确认这些是准确的
library(car)
dataEllipse(x, y, levels=0.95)