r - glm - R 中的异常值检测和删除

标签 r glm outliers diagnostics

我构建了一个二元逻辑模型。响应变量是二进制的。有 4 个回归量 - 2 个二进制和 2 个整数。我想找到异常值并将其删除。为此,我创建了一些图:

  par(mfrow = c(2,2))
  plot(hat.ep,rstudent.ep,col="#E69F00", main="hat-values versus studentized residuals",
       xlab="Hat value", ylab="Studentized residual")
  dffits.ep <- dffits(model_logit)
  plot(id,dffits.ep,type="l", col="#E69F00", main="Index Plot",
       xlab="Identification", ylab="Diffits")
  cov.ep <- covratio(model_logit)
  plot(id,cov.ep,type="l",col="#E69F00",  main="Covariance Ratio",
       xlab="Identification", ylab="Covariance Ratio")
  cook.ep <- cooks.distance(model_logit)
  plot(id,cook.ep,type="l",col="#E69F00", main="Cook's Distance",
       xlab="Identification", ylab="Cook's Distance")

enter image description here

根据绘图,存在异常值。 如何识别哪个观测值是异常值?

我已经尝试过:

>   outlierTest(model_logit)
No Studentized residuals with Bonferonni p < 0.05
Largest |rstudent|:
     rstudent unadjusted p-value Bonferonni p
1061 1.931043           0.053478           NA

还有其他一些用于异常值检测的函数吗?

最佳答案

这个答案来得太晚了。我不确定你是否找到了答案。继续进一步,在没有 minimum reproducible example 的情况下,我将尝试使用一些虚拟数据和两个自定义函数来回答这个问题。对于给定的连续变量,异常值是指位于 1.5*IQR 之外的观测值,其中 IQR(“四分位数间距”)是第 75 个四分位数和第 25 个四分位数之间的差值。我还推荐你看看这个post包含比我粗略的答案更好的解决方案。

> df <- data.frame(X = c(NA, rnorm(1000), runif(20, -20, 20)), Y = c(runif(1000),rnorm(20, 2), NA), Z = c(rnorm(1000, 1), NA, runif(20)))
> head(df)
         X      Y      Z
1       NA 0.8651 0.2784
2 -0.06838 0.4700 2.0483
3 -0.18734 0.9887 1.8353
4 -0.05015 0.7731 2.4464
5  0.25010 0.9941 1.3979
6 -0.26664 0.6778 1.1277

> boxplot(df$Y) # notice the outliers above the top whisker

boxplot with outliers

现在,我将创建一个自定义函数来检测异常值,另一个函数将用 NA 替换异常值。

# this function will return the indices of the outlier values
> findOutlier <- function(data, cutoff = 3) {
  ## Calculate the sd
  sds <- apply(data, 2, sd, na.rm = TRUE)
  ## Identify the cells with value greater than cutoff * sd (column wise)
  result <- mapply(function(d, s) {
    which(d > cutoff * s)
  }, data, sds)
  result
}

# check for outliers
> outliers <- findOutlier(df)

# custom function to remove outliers
> removeOutlier <- function(data, outliers) {
  result <- mapply(function(d, o) {
    res <- d
    res[o] <- NA
    return(res)
  }, data, outliers)
  return(as.data.frame(result))
}

> filterData<- removeOutlier(df, outliers)
> boxplot(filterData$Y)

boxplot with outlier removed

关于r - glm - R 中的异常值检测和删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50060644/

相关文章:

r - 使用ggplot2为每组添加回归线

r - 为什么R中有两个赋值运算符 `<-`和 `->`?

python-3.x - 如何删除异常值

r - 如何从这些对象的列表中创建对象属性的新列表?

r - 将列值转换为 R 中的日期

python - rpy2 + 负二项式 glm

python - 从列表中检测异常值

java - 基于增量模型的异常值检测

r - 如何引导被一个因素阻止的 R 中的数据集?

R:VGAM 中的不兼容尺寸错误 vglm 函数