私は大規模なデータセットを持っており、99 パーセンタイルを超える値または 1 パーセンタイルを下回る値を外れ値と定義しました。
これらの外れ値の平均を前後のデータポイントで取得し、3 つの値すべてを新しいデータセットのその平均に置き換えたいと思います。
これを行う方法を知っている人がいる場合は、応答していただければ幸いです。
ベクトル内の外れ値の位置を指定するインデックスのリストがある場合、たとえば次を使用します。
out_idx = which(df$value > quan0.99)
次のようなことができます:
for(idx in out_idx) {
vec[(idx-1):(idx+1)] = mean(vec[(idx-1):(idx+1)])
}
これを関数でラップして、帯域幅と関数をオプションのパラメーターにすることができます。
average_outliers = function(vec, outlier_idx, bandwith, func = "mean") {
# iterate over outliers
for(idx in out_idx) {
# slicing of arrays can be used for extracting information, or in this case,
# for assiging values to that slice. do.call is used to call the e.g. the mean
# function with the vector as input.
vec[(idx-bandwith):(idx+bandwith)] = do.call(func, out_idx[(idx-bandwith):(idx+bandwith)])
}
return(vec)
}
帯域幅 2 で使用することもできますmedian
。この関数を使用すると、次のようになります。
# Call average_outliers multiple times on itself,
# first for the 0.99 quantile, then for the 0.01 quantile.
vec = average_outliers(vec, which(vec > quan0.99))
vec = average_outliers(vec, which(vec < quan0.01))
また:
vec = average_outliers(vec, which(vec > quan0.99), bandwith = 2, func = "median")
vec = average_outliers(vec, which(vec < quan0.01), bandwith = 2, func = "median")
2 の帯域幅を使用し、中央値に置き換えます。