maycca
maycca

Reputation: 4080

Function to remove outliers by group from dataframe

I am trying to remove the outliers from my dataframe containing x and y variables grouped by variable cond.

I have created a function to remove the outliers based on a boxplot statistics, and returning df without outliers. The function works well when applied for a raw data. However, if applied on grouped data, the function does not work and I got back an error:

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

Please, how can I correct my function to take vectors df$x and df$y as arguments, and correctly get rid of outliers by group?

enter image description here


My dummy data:

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)

I have found this function to remove the outliers from a vector data . However, I would like to remove outliers from both df$x and df$y vectors in a dataframe.

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)

Upvotes: 3

Views: 3048

Answers (2)

Birger
Birger

Reputation: 1141

You may just filter your data:

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()

Created on 2018-12-11 by the reprex package (v0.2.1)

Upvotes: 3

YOLO
YOLO

Reputation: 21709

Since you are applying this function to entire df, you should instead use mutate_all. Do:

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

Upvotes: 5

Related Questions