r - 如何使用通用方法仅删除 R 中存在的异常值

标签 r boxplot outliers

我正在使用一种方法来删除单变量异常值。此方法仅在向量包含异常值时才有效。

如何才能将此方法推广到也适用于没有异常值的向量。我尝试使用 ifelse 但没有成功。

library(tidyverse)

df <- tibble(x = c(1,2,3,4,5,6,7,80))

outliers <- boxplot(df$x, plot=FALSE)$out
print(outliers)
#> [1] 80

# This removes the outliers
df2 <- df[-which(df$x %in% outliers),]

# a new tibble withou outliers
df3 <- tibble(x = c(1,2,3,4,5,6,7,8))

outliers3 <- boxplot(df3$x, plot=FALSE)$out
print(outliers3) # no outliers
#> numeric(0)

# if I try to use the same expression to remove 0 outliers
df4 <- df[-which(df3$x %in% outliers),]

# boxplot gives an error because df4 has 0 observations
# when I was expecting 8 observations
boxplot(df4$x)
#> Warning in min(x): no non-missing arguments to min; returning Inf
#> Warning in max(x): no non-missing arguments to max; returning -Inf
#> Error in plot.window(xlim = xlim, ylim = ylim, log = log, yaxs = pars$yaxs): need finite 'ylim' values

最佳答案

求反 (!) 而不是使用 -,即使没有异常值也可以工作

df3[!(df3$x %in% outliers3),]

-输出

# A tibble: 8 x 1
      x
  <dbl>
1     1
2     2
3     3
4     4
5     5
6     6
7     7
8     8

或者如果存在异常值,则会删除

df[!df$x %in% outliers,]
# A tibble: 7 x 1
      x
  <dbl>
1     1
2     2
3     3
4     4
5     5
6     6
7     7

关于r - 如何使用通用方法仅删除 R 中存在的异常值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67992709/

相关文章:

r - 对于数据帧行的直方图,“x”必须是数字

r - 为多个组生成具有不同颜色的ggplot2 boxplot

r - 过滤季节性时间序列异常值

python - 在Python中删除异常值并计算具有不同实际值数量的多列的修剪平均值

删除十进制格式中多余的字符串字符

来自串联的 R 项目文件路径

r - 如何在r中的箱线图之间创建单独的线图

r - 如何在箱线图中创建组之间的空间并控制轴标签的大小?

python - 检测和排除 pandas DataFrame 中的异常值

r - plotly 上没有创建线性趋势线