删除不同组的离群值

时间:2019-12-12 20:00:59

标签: r outliers

我在这里很陌生,所以请宽容我:-)

我正在寻找一种解决方案,以删除在同一列中相差某个值的离群值:

body_mass age 1 19 11 2 20 10 3 26 8 4 21 6 5 18 12 6 18 7 7 30 11 8 17 8 9 17 10 10 18 8

every age has different outliers - so what is a normal value (body_mass) for age 4, may be an outlier for age 0...

boxplot(body_mass~age, data = df, subset=age %in% c(0:22))$out
outliers <- boxplot(body_mass~age, data = df, subset=age %in% c(0:22))$out

df[which(df$body_mass %in% outliers),]
df <- df[-which(df$body_mass %in% outliers),]

但是尝试这种方法,会删除所有年龄段的所有值,即使它们只是一个年龄段的离群值

1 个答案:

答案 0 :(得分:0)

这实际上取决于您如何定义“异常值”。但是如果你愿意接受 离群值是四分位数范围的正负1.5倍,那么您可以使用以下方法按年龄段去除体重中的离群值。

此外,我假设您想将每个年龄都视为一个单独的组,因为您没有另外指明。

定义一个函数,该函数将用NA替换离群值。

#' Replace outliers
#'
#' Replace outliers with NA. Outliers are defined as values that fall outside plus or minus
#' 1.5 * IQR.
#'
#' @return Numeric vector of same length.
#' @param x Numeric vector to replace.
#' @param na.rm Should NA values be replaced beforehand?
#'
#' @export
remove_outliers <- function(x, na.rm = TRUE, ...) {
  qnt <- quantile(x, probs = c(.25, .75), na.rm = na.rm, ...)
  val <- 1.5 * IQR(x, na.rm = na.rm)
  y <- x
  y[x < (qnt[1] - val)] <- NA
  y[x > (qnt[2] + val)] <- NA
  y
}

按年龄段和过滤条件应用remove_outliers()

library(dplyr)

df2 <- df %>% 
  group_by(age) %>% 
  mutate(body_mass = replace_outliers(body_mass)) %>% 
  ungroup() %>% 
  filter(!is.na(body_mass))
相关问题