r - 仅当 R 中存在异常值时,如何使用通用方法删除异常值
问题描述
我正在使用一种方法来删除单变量异常值。此方法仅在向量包含异常值时有效。
如何将这种方法推广到也适用于没有异常值的向量。我试过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
解决方案
即使没有异常值,也可以使用否定( !
) 而不是使用which-
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
推荐阅读
- python - 根据关键字搜索列表以附加特定列表内容
- laravel - 我在网络路由中遇到 slug 和 id 问题
- c++ - c ++文件读/写无限循环,再次重写txt
- javascript - JavaScript 遍历嵌套对象以获取值高于给定数字的键
- reactjs - 我的 React 网页在 iframe 中不起作用
- html - 如何为显示按钮创建 CSS 悬停效果
- python - 如何使用 Pygame 绘制旋转椭圆?
- jquery - 样式类不适用于 Laravel 输出中的 jquery append 元素
- spring-data-jpa - 将 gRPC 与 Spring Data Jpa 集成以实现持久层
- unity3d - 从 Blender 导入 Unity 的模型不一样