从数据框中按组删除异常值的功能

Function to remove outliers by group from dataframe

我正在尝试从包含按变量 cond 分组的 xy 变量的数据框中删除异常值。

我创建了一个函数来根据箱线图统计数据删除异常值,并返回 df 没有异常值。该函数在应用于原始数据时效果很好。但是,如果应用于分组数据,该函数将不起作用,我得到一个错误:

Error in mutate_impl(.data, dots) : 
  Evaluation error: argument "df" is missing, with no default.

请问,我该如何更正我的函数以将向量 df$xdf$y 作为参数,并正确地按组去除异常值?


我的虚拟数据:

set.seed(955)
# Make some noisily increasing data
dat <- data.frame(cond = rep(c("A", "B"), each = 22),
                  xvar = c(1:10+rnorm(20,sd=3), 40, 10, 11:20+rnorm(20,sd=3), 85, 115),
                  yvar = c(1:10+rnorm(20,sd=3), 200, 60, 11:20+rnorm(20,sd=3), 35, 200))


removeOutliers<-function(df, ...) {

  # first, identify the outliers and store them in a vector
  outliers.x<-boxplot.stats(df$x)$out
  outliers.y<-boxplot.stats(df$y)$out

  # remove the outliers from the original data
  df<-df[-which(df$x %in% outliers.x),]
  df[-which(df$y %in% outliers.y),]
}

# REmove outliers (try if function works)
removeOutliers(dat)

# Apply the function to group
# Not working!!!

dat_noOutliers<- dat %>%
  group_by(cond) %>%
  mutate(removeOutliers)

我发现这个函数可以从矢量数据中删除异常值。但是,我想从数据框中的 df$xdf$y 向量中删除异常值。

remove_outliers <- function(x, na.rm = TRUE, ...) {
  qnt <- quantile(x, probs=c(.25, .75), na.rm = na.rm, ...)
  H <- 1.5 * IQR(x, na.rm = na.rm)
  y <- x
  y[x < (qnt[1] - H)] <- NA
  y[x > (qnt[2] + H)] <- NA
  y
}

(remove outliers by group in R)

由于您将此函数应用于整个 df,因此您应该改用 mutate_all。做:

dat_noOutliers<- dat %>%
  group_by(cond) %>%
  mutate_all(remove_outliers)

您可以只过滤您的数据:

library(tidyverse)

set.seed(955)
dat <- data.frame(cond = rep(c("A", "B"), each = 22),
                  xvar = c(1:10+rnorm(20,sd=3), 40, 10, 11:20+rnorm(20,sd=3), 85, 115),
                  yvar = c(1:10+rnorm(20,sd=3), 200, 60, 11:20+rnorm(20,sd=3), 35, 200))

dat %>%
  ggplot(aes(x = xvar, y = yvar)) + 
  geom_point() + 
  geom_smooth(method = lm) +
  ggthemes::theme_hc()

dat %>%
  group_by(cond) %>%
  filter(!xvar %in% boxplot.stats(xvar)$out) %>%
  filter(!yvar %in% boxplot.stats(yvar)$out) %>%
  ggplot(aes(x = xvar, y = yvar)) + 
  geom_point() + 
  geom_smooth(method = lm) +
  ggthemes::theme_hc()

reprex package (v0.2.1)

创建于 2018-12-11