我希望能替换掉在我的相对较大的 R 数据集中取值在第95个和第5个百分位之上或之下的所有数值,使它们分别等于这些百分位的数值。 我的目标是避免完全删去数据中的离群值。
如有建议,十分感谢。我在其他地方找不到如何做到这一点的信息。
fun <- function(x){
quantiles <- quantile( x, c(.05, .95 ) )
x[ x < quantiles[1] ] <- quantiles[1]
x[ x > quantiles[2] ] <- quantiles[2]
x
}
fun( yourdata )
squish()
一行代码完成它:d2 <- squish(d, quantile(d, c(.05, .95)))
在 Scales 库中,查看 ?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
cap <- function(x, low, high) pmin(high, pmax(low, x))
- Benqn = 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
是您的数据框,value
是包含您的数据的列。
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
=
作为赋值运算符。<-
可以复合,但=
дёЌиЎЊгЂ‚ - Ricardo Saporta=
,很少遇到问题。只有在像system.time(bla <- spam())
这样的调用中,<-
是必需的。 - Paul Hiemstra