【问题标题】:How to identify and remove outliers in a data.frame using R?如何使用 R 识别和删除 data.frame 中的异常值?
【发布时间】:2021-11-09 21:15:36
【问题描述】:

我有一个包含多个异常值的数据框。我怀疑这些 oulier 产生的结果与预期不同。

我尝试使用此技巧,但它不起作用,因为我仍然有非常不同的值:https://www.r-bloggers.com/2020/01/how-to-remove-outliers-in-r/

我尝试了使用 rstatix 包的解决方案,但我无法从我的 data.frame 中删除异常值

library(rstatix)
library(dplyr)

df <- data.frame(
  sample = 1:20,
  score = c(rnorm(19, mean = 5, sd = 2), 50))

View(df)

out_df<-identify_outliers(df$score)#identify outliers

df2<-df#copy df

df2<- df2[-which(df2$score %in% out_df),]#remove outliers from df2

View(df2)

【问题讨论】:

  • 您的预期输出是什么。你说你想删除异常值,这就是它正在做的事情

标签: r outliers rstatix


【解决方案1】:

identify_outliers 期望一个 data.frame 作为输入,即用法是

identify_outliers(data, ..., variable = NULL)

在哪里

... - 一个不带引号的表达式(或变量名)。用于选择感兴趣的变量。替代参数变量。

df2 <- subset(df, !score %in% identify_outliers(df, "score")$score)

【讨论】:

  • 嗨@Akrun。我测试了该命令,它只是识别异常值。我也希望他删除。
  • @wesleysc352 在这种情况下,只需否定 (!)(更新)
  • @wesleysc352 我假设你想使用rstatix
【解决方案2】:

根据经验,高于 Q3 + 1.5xIQR 或低于 Q1 - 1.5xIQR 的数据点被视为异常值。 因此,您只需要识别它们并删除它们。我不知道如何使用依赖 rstatix 来做到这一点,但是可以按照下面的示例实现 base R:

# Generate a demo data
set.seed(123)
demo.data <- data.frame(
                         sample = 1:20,
                         score = c(rnorm(19, mean = 5, sd = 2), 50),
                         gender = rep(c("Male", "Female"), each = 10)
                        )
#identify outliers
outliers <- which(demo.data$score > quantile(demo.data$score)[4] + 1.5*IQR(demo.data$score) | demo.data$score < quantile(demo.data$score)[2] - 1.5*IQR(demo.data$score)) 

# remove them from your dataframe
df2 = demo.data[-outliers,]

执行一个更酷的函数,返回异常值的索引:

get_outliers = function(x){
   which(x > quantile(x)[4] + 1.5*IQR(x) | x < quantile(x)[2] - 1.5*IQR(x))
}

outliers <- get_outliers(demo.data$score)


df2 = demo.data[-outliers,]

【讨论】:

  • 您的回复与@Akru 的回复有何不同?
  • 我明确地向您展示了异常值的经验法则,并且在没有依赖关系的情况下明确删除数据框中的异常值行。
猜你喜欢
  • 2021-12-26
  • 2013-05-07
  • 1970-01-01
  • 2019-04-11
  • 2012-08-11
  • 2019-07-27
  • 2016-06-10
  • 2018-10-08
  • 2012-06-23
相关资源
最近更新 更多