如何使用 R 检测和替换单个数据集中多列的异常值?

How to detect and replace outlier from multiple columns in a single data set using R?

我正在尝试查找并替换多个数字列中的异常值。根据我的拙见,这不是最佳实践,但这是我试图针对特定用例找出的东西。 但是 可以找到创建附加列以将行标记为离群值的一个很好的示例,但它基于单个列。

我的数据如下(为简单起见,我排除了带有因子的列):

   Row ID   Value1 Value2
      1        6      1
      2        2     200
      3      100      3
      4        1      4
      5      250      5
      6        2      6
      7        8     300
      8      600     300
      9        2      9

我使用函数将所有数字列中的离群值替换为 NA:

replaceOuts = function(df) {
    map_if(df, is.numeric, 
           ~ replace(.x, .x %in% boxplot.stats(.x)$out, NA)) %>% 
    bind_cols 
}
test = replaceOuts(df)

我的问题是如何用另一个值(例如,平均值、中值、上限值等)替换异常值?如有任何帮助,我们将不胜感激!

我认为您需要 minVal 和 max 最大阈值。然后将超出范围的值 (minVal, maxVal) 替换为 Value 中的任何值(平均值,中位数或您需要的值)

# Could be any value for limits, i.e. 
minVal <- boxplot.stats(data$columnX)$stats[1]
maxVal <- boxplot.stats(data$columnX)$stats[5]
myValue <- median(data$columnX)

data[data$columnX < minVal | data$columnX > maxVal, "columnX"] <- myValue   

而不是 NA 您可以用 meanmedian 替换您喜欢的任何值。

library(dplyr)
library(purrr)

replaceOuts = function(df) {
   map_if(df, is.numeric, 
          ~ replace(.x, .x %in% boxplot.stats(.x)$out, mean(.x))) %>%
   bind_cols 
}

replaceOuts(df)

# RowID Value1 Value2
#  <dbl>  <dbl>  <dbl>
#1     1     6       1
#2     2     2     200
#3     3   100       3
#4     4     1       4
#5     5   108.      5
#6     6     2       6
#7     7     8     300
#8     8   108.    300
#9     9     2       9

mean 替换为 median 到您想要的任何其他函数。

PS - 我认为最好在这里使用 mutate_if 而不是 map_if,因为它避免了最后的 bind_cols

df %>% mutate_if(is.numeric, ~replace(., . %in% boxplot.stats(.)$out, mean(.)))