gl - 在R中检测和去除异常值

时间:2018-04-27 10:40:01

标签: 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

是否还有其他一些异常值检测功能?

1 个答案:

答案 0 :(得分:0)

这个答案来得太晚了。我不确定您是否找到答案。接下来,在没有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

相关问题