-->

如何更换与R中的第5和第95百分位值异常(How to replace outliers with

2019-08-02 14:49发布

我想分别替换所有值在我相对很大的R数据集,其采取上述第95和下面的第5百分位数值,这些百分比值。 我的目的是为了避免简单地从完全的数据裁剪这些异常值。

任何意见将不胜感激,我无法找到如何做到这一点其他任何​​地方的任何信息。

Answer 1:

这将做到这一点。

fun <- function(x){
    quantiles <- quantile( x, c(.05, .95 ) )
    x[ x < quantiles[1] ] <- quantiles[1]
    x[ x > quantiles[2] ] <- quantiles[2]
    x
}
fun( yourdata )


Answer 2:

您可以通过做在一行代码squish()

d2 <- squish(d, quantile(d, c(.05, .95)))



在秤图书馆,看?squish?discard

#--------------------------------
library(scales)

pr <- .95
q  <- quantile(d, c(1-pr, pr))
d2 <- squish(d, q)
#---------------------------------

# Note: depending on your needs, you may want to round off the quantile, ie:
q <- round(quantile(d, c(1-pr, pr)))

例:

d <- 1:20
d
# [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20


d2 <- squish(d, round(quantile(d, c(.05, .95))))
d2
# [1]  2  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 19


Answer 3:

我用这个代码来获取你所需要的:

qn = quantile(df$value, c(0.05, 0.95), na.rm = TRUE)
df = within(df, { value = ifelse(value < qn[1], qn[1], value)
                  value = ifelse(value > qn[2], qn[2], value)})

其中df是你的data.frame,和value包含您的数据的列。



Answer 4:

有一个更好的办法来解决这个问题。 离群值不超过第95百分位或低于第5百分位的任何一点。 相反,异常值被认为是这样,如果它是第一个四分位数以下 - 1.5·IQR或以上第三个四分位数+ 1.5·IQR。
这个网站将介绍更彻底

要了解更多关于治疗离群这里指

capOutlier <- function(x){
   qnt <- quantile(x, probs=c(.25, .75), na.rm = T)
   caps <- quantile(x, probs=c(.05, .95), na.rm = T)
   H <- 1.5 * IQR(x, na.rm = T)
   x[x < (qnt[1] - H)] <- caps[1]
   x[x > (qnt[2] + H)] <- caps[2]
   return(x)
}
df$colName=capOutlier(df$colName)
Do the above line over and over for all of the columns in your data frame


文章来源: How to replace outliers with the 5th and 95th percentile values in R