Count rows satisfying "less than" filter for sequence of values

Viewed 309

I have a dataset with a bunch of times. Let's say I wanted to create a summary table that counts number of rows satisfying "less than" filter for a sequence of values, say [number of rows with time < 6, number of rows with time < 7, etc.]

Example dataset:

data.frame(personId = c("2009ZEMD01", "2012PARK03", "2017VILL41", "2010WEYE01", "2016KOLA02", "2012PONC02"), 
           average = c(553, 559, 598, 606, 612, 613))

This was my solution using sapply:

  tibble(time = 6:15, 
         count = sapply(time, function(t) best_3x3_solvers %>% filter(average/100 < t) %>% nrow)) 

The result:

> solvers_under
# A tibble: 10 x 2
    time count
   <int> <int>
 1     6     3
 2     7    48
 3     8   274
 4     9   840
 5    10  1952
 6    11  3792
 7    12  6269
 8    13  9459
 9    14 13204
10    15 17274

The code is not too long but is there a method using more tidyverse tools without *apply? Maybe summarize with n().

3 Answers

One dplyr and purrr option could be:

map_dfr(.x = 6:15,
        ~ df %>%
         group_by(time = .x) %>%
         summarise(count = sum(average/100 < .x)))

    time count
   <int> <int>
 1     6     3
 2     7     6
 3     8     6
 4     9     6
 5    10     6
 6    11     6
 7    12     6
 8    13     6
 9    14     6
10    15     6

Here's one way :

library(dplyr)
library(purrr)

map_df(6:15, ~df %>% summarise(time = .x, count = sum(average/100 < .x)))

#    time count
# 1     6     3
# 2     7     6
# 3     8     6
# 4     9     6
# 5    10     6
# 6    11     6
# 7    12     6
# 8    13     6
# 9    14     6
#10    15     6

You can use summarise, count and filter

df%>%group_by(time)%>%summarise(count = n())%>%filter(count < t)
Related