Jacob Odom
Jacob Odom

Reputation: 216

Find number of points outside a threshold within groups

##generate test data
mtcars <- mtcars
mtcars$meanmpg <- mean(mtcars$mpg)

Now I wish to generate a column numpoints for the number of points within a group that fall outside -2 and + 5 of the mean.

 mutated <- mtcars %>% group_by(cyl) %>%
 mutate(numpoints = length( which( .$mpg < (.$meanmpg - 2) | .$mpg > (.$meanmpg + 5) ) )  )

For example, I would see 6 in the column numpoints for the "4 cyl group", and 1 for the "6 cyl group". (less than mean mpg - 2 or greater than mean mpg + 5)

any ideas? I also tried filter but can't figure out a way to keep all my data after the filter.

Upvotes: 2

Views: 53

Answers (2)

ARobertson
ARobertson

Reputation: 2897

Base R is pretty simple:

# get data
data(mtcars)

# get mean
meanmpg <- mean(mtcars$mpg)

# calculate min/max threshold
mtcars$outsidethreshold <- (mtcars$mpg - meanmpg) > 5 | (mtcars$mpg - meanmpg) < -2

# get sum by group with ave
mtcars$numpoints <- ave(mtcars$outsidethreshold,mtcars$cyl,FUN = sum)

Upvotes: 1

lukeA
lukeA

Reputation: 54237

Now I wish to generate a column numpoints for the number of points within a group that fall outside -2 and + 5 of the mean.

I'd try

library(dplyr)
mtcars %>% 
  group_by(cyl) %>%
  mutate(numpoints = sum(!between(mpg, meanmpg-2, meanmpg+5)))
# Source: local data frame [32 x 13]
# Groups: cyl [3]
# 
#      mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb  meanmpg numpoints
#    <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>    <dbl>     <int>
# 1   21.0     6 160.0   110  3.90 2.620 16.46     0     1     4     4 20.09062         1
# 2   21.0     6 160.0   110  3.90 2.875 17.02     0     1     4     4 20.09062         1
# 3   22.8     4 108.0    93  3.85 2.320 18.61     1     1     4     1 20.09062         6
# 4   21.4     6 258.0   110  3.08 3.215 19.44     1     0     3     1 20.09062         1
# 5   18.7     8 360.0   175  3.15 3.440 17.02     0     0     3     2 20.09062        12
# 6   18.1     6 225.0   105  2.76 3.460 20.22     1     0     3     1 20.09062         1
# 7   14.3     8 360.0   245  3.21 3.570 15.84     0     0     3     4 20.09062        12
# 8   24.4     4 146.7    62  3.69 3.190 20.00     1     0     4     2 20.09062         6
# 9   22.8     4 140.8    95  3.92 3.150 22.90     1     0     4     2 20.09062         6
# 10  19.2     6 167.6   123  3.92 3.440 18.30     1     0     4     4 20.09062         1
# ..   ...   ...   ...   ...   ...   ...   ...   ...   ...   ...   ...      ...       ...

Upvotes: 2

Related Questions