【问题标题】:R outliers functionR异常值函数
【发布时间】:2018-08-30 12:05:24
【问题描述】:

我有一个删除异常值detectaOutliers() 的函数,但不知何故我的函数并没有删除所有异常值。

谁能帮我找出错误?

detectaOutliers = function(x) {
  q = quantile(x, probs = c(0.25, 0.75))
  R = IQR(x)
  OM1 = q[1] - (R * 1.5)  # outliers moderados
  OM3 = q[2] + (R * 1.5)
  OE1 = q[1] - (R * 3)    # outliers  extremos
  OE3 = q[2] + (R * 3)

  moderados = ifelse(x < OM1 | x > OM3, 1, 0)  
  extremos  = ifelse(x < OE1 | x > OE3, 1, 0)  
  cbind(extOut = moderados)
}


cepas = unique(AbsExtSin$Cepa)
concs = unique(AbsExtSin$Concen)
outliers = NULL
for (cepa in cepas) {
    for (concen in concs) {
      datosOE = subset(AbsExtSin, Cepa == cepa & Concen == concen)
      outs = detectaOutliers(datosOE$Abs)

      datosOE  = cbind(datosOE, outs)
      outliers = rbind(outliers, datosOE)
    }
}
AbsExtSin = subset(outliers, extOut == 0)[, 1:5]

这是没有异常值的数据(我删除了11个异常值,但我还有更多)

【问题讨论】:

  • 我不明白出了什么问题,您的函数给出的异常值与 detOutliers = function(x) boxplot(x, plot = FALSE)$out 相同。

标签: r function boxplot outliers


【解决方案1】:

回答: 我假设您的问题如下:首先,您检测异常值(就像 boxplot 函数一样)并删除它们。之后,您使用清理后的数据生成箱线图,再次显示异常值。而且您希望看到没有异常值。

这不一定是您的代码错误,这是您期望的错误。当您删除异常值时,数据集的统计数据会发生变化。例如,四分位数不再相同。因此,您可能会识别出“新的”异常值。请参阅以下示例:

## create example data
set.seed(12345)
rand <- rexp(100,23)
## plot. gives outliers.
boxplot(rand)
## detect outliers with these functions
detectaOutliers = function(x) {
  q = quantile(x, probs = c(0.25, 0.75))
  R = IQR(x)
  OM1 = q[1] - (R * 1.5)  # outliers moderados
  OM3 = q[2] + (R * 1.5)
  OE1 = q[1] - (R * 3)    # outliers  extremos
  OE3 = q[2] + (R * 3)

  moderados = ifelse(x < OM1 | x > OM3, 1, 0)  
  extremos  = ifelse(x < OE1 | x > OE3, 1, 0)  
  cbind(extOut = moderados)
}
detectOut <- function(x) boxplot(x, plot = FALSE)$out
## clean your data
clean1 <- rand[!as.logical(detectaOutliers(rand))]
clean2 <- rand[!rand%in%detectOut(rand)]
## check that these functions do the same.
all(clean1  == clean2 )
# Fun fact: depending on your data, clean1 and clean2
# are not always the same. See the extra note below.
## plot cleaned data
boxplot(clean2)
## Still has outliers. But "new" ones. confirm with:
sort(boxplot(rand)$out) # original outlier
sort(boxplot(clean2)$out) # new outlier

注 1: 您的代码不一定使用与 R 中的 boxplot 函数相同的异常值标识(我不确定 ggplot boxplot,但至少对于 graphics::boxplot 函数是这样。):

## The boxplot function (rather: boxplot.stats)
## does not use the quantile function, but the fivenum function
## to identify outliers. They produce different results, e.g., here:
fivenum(rand)[c(2,4)]
quantile(rand,probs=c(0.25,0.75))

注意 2: 如果您想要排除异常值的箱线图,可以使用箱线图函数的outline 参数(对于ggplot,请参阅Ignore outliers in ggplot2 boxplot

【讨论】:

    【解决方案2】:

    6 小时后,我意识到错误出在我正在使用的变量中(我的数据库有 4 个变量,我需要单独删除一列的异常值,这取决于另外两个,结果证明我错了我选择的2个)终于实现了,功能完美!

    感到不便,非常感谢大家

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-13
      • 2022-01-11
      • 2019-10-19
      • 1970-01-01
      • 2017-01-31
      • 2020-08-23
      • 2020-07-21
      • 1970-01-01
      相关资源
      最近更新 更多