R using which function after group_by

Viewed 44

I have a dataset with four variables (a,b,c,d). I want to group the data by a,b,c then find out outliers for d.

Here is the sample data: https://www.dropbox.com/s/ftp4eehqxzh7nn3/example.csv?dl=0

I tried:

outliers = data %>%
           group_by(a,b,c) %>%
           which (data$d > quantile (data$d, na.rm=T)[4] + 1.5*IQR(data$d, na.rm = T) | data$d < quantile (data$d, na.rm=T)[2] - 1.5*IQR(data$d, na.rm = T).

However, I got error argument to 'which' is not logical.

Would appreciate if anyone can tell me what I got wrong and how should I fix the problem.

1 Answers

You could use

library(dplyr)

data %>%
  group_by(a,b,c) %>%
  filter(
    d > quantile(d, na.rm = TRUE)[4] + 1.5 * IQR(d, na.rm = TRUE) | 
      d < quantile(d, na.rm = TRUE)[4] - 1.5 * IQR(d, na.rm = TRUE))

This returns you

# A tibble: 2,464 x 5
    ...1 a         d b         c
   <dbl> <chr> <dbl> <chr> <dbl>
 1 10533 gas   321.  CAISO  2011
 2 10534 gas    51.8 CAISO  2012
 3 15067 gas    52.6 CAISO  2013
 4 25890 oil    51.0 ISONE  2010
 5 26485 gas   416.  PJM    2008
 6 26489 gas   468.  PJM    2012
 7 38153 gas   Inf   SPP    2014
 8 38154 gas   Inf   SPP    2015
 9 38155 gas    67.4 SPP    2016
10 38156 gas    58.8 SPP    2017
# ... with 2,454 more rows
Related