R语言查找rs与hat符合条件元素索引及散点图标注方法
筛选符合条件的索引
你可以通过组合逻辑条件+which()函数直接获取目标索引,筛选逻辑为:学生化残差rs绝对值大于1.96,且对应的hat值大于阈值max_hat,代码如下:
# 原有数据加载与阈值计算部分 x <- readRDS(url("https://github.com/rnorouzian/s/raw/main/cooks.rds")) hat <- readRDS(url("https://github.com/rnorouzian/s/raw/main/hat.rds")) rs <- readRDS(url("https://github.com/rnorouzian/s/raw/main/rstudent.rds"))$z max_hat <- boxplot.stats(hat, coef = 2)$stats[5] # 筛选目标索引 target_idx <- which(abs(rs) > 1.96 & hat > max_hat) # 打印索引结果 print(target_idx)
散点图标注索引
可以直接使用text()函数完成标注,为了避免标注遮挡散点,可设置标注位置在点的右侧,完整绘图代码如下:
# 绘制基础散点图 plot(hat, rs, cex = 0.2+3*sqrt(x), pch = 19, xlab = "Hat值", ylab = "学生化残差") # 标注符合条件的点位索引 text( x = hat[target_idx], y = rs[target_idx], labels = target_idx, pos = 4, # 1=下 2=左 3=上 4=右 col = "red", cex = 0.8 ) # 可选:添加阈值参考线方便对照 abline(h = c(-1.96, 1.96), lty = 2, col = "darkgray") abline(v = max_hat, lty = 2, col = "darkgray")
内容的提问来源于stack exchange,提问作者Simon Harmel
相关产品推荐
相关产品推荐

