查找组内阈值以外的点数

时间:2016-07-06 20:06:50

标签: r dplyr

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

现在我希望为组内的点数生成一个列numpoints,它们落在-2和+ 5的平均值之外。

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

例如,我会在&#34; 4 cyl组&#34;的列numpoints中看到6,在#34; 6 cyl组&#34;中看到1。 (小于平均mpg - 2或大于平均mpg + 5)

任何想法?我也尝试过滤,但无法找到一种方法来保留过滤后的所有数据。

2 个答案:

答案 0 :(得分:2)

  

现在我希望为点数生成列numpoints   在一组中,落在平均值的-2和+5之外。

我试试

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
# ..   ...   ...   ...   ...   ...   ...   ...   ...   ...   ...   ...      ...       ...

答案 1 :(得分:1)

Base R非常简单:

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