在线性模型的汇总图中,如何用分组变量而不是索引值来标记异常值?

In summary plots of a linear model, how to label outliers with a grouping variable instead of the index value?

我有一个结构如下的数据框:

set.seed(123)
data<- data.frame(
  ID=factor(letters[seq(20)]),
  Location = rep(c("alph","brav", "char","delt"), each = 5),
  Var1 = rnorm(20),
  Var2 = rnorm(20),
  Var3 = rnorm(20)
)  

我建立了一个线性模型:mod1 <- lm(Var1~Location,mydata)。当我在线性模型对象上使用: plot(mod1) 时,离群值被标记为值的索引。有没有办法用 ID 中的值标记这些点?换句话说,在此示例中,图中标记了值 6、16 和 18,我希望它们分别标记为 f、p 和 r,因为这些是它们在 ID 中的对应值

stats:::plot.lm用于绘制诊断图,有两种选择:

id.n: number of points to be labelled in each plot, starting with
      the most extreme.

labels.id: vector of labels, from which the labels for extreme points
          will be chosen.  ‘NULL’ uses observation numbers.

默认情况下 id.n=3,所以他们总是标记厨师距离最大的 3 个观测值。我将此作为答案的一部分包括在内,因为您可能需要小心地将它们解释为异常值。

要获得这些积分,您需要

mod1 <- lm(Var1~Location,data)
outl = order(-cooks.distance(mod1))[1:3]
outl
[1] 18  6 16

要绘图,您可以提供 labels.id 您想要的 ID,或者从头开始:

par(mfrow=c(1,2))
plot(mod1,which=1,labels.id =data$ID)
plot(fitted(mod1),residuals(mod1))
panel.smooth(fitted(mod1),residuals(mod1))
text(fitted(mod1)[outl]+0.01,residuals(mod1)[outl],
data$ID[outl],col="red")

要遍历所有图,请执行以下操作:

plot(mod1,labels.id=data$ID)