Q:

how to subset dataframe based on vector and then group by in dplyr

I have following dataframe in R
 ID        Blocks
 123       2D
 345       2E
 324       2D
 567       4F
 678       5E
 444       2D
 145       2D

Now I want to subset dataframe based on a vector and then on each subset I want to apply group by
e.g    vec <- c(2,3,2) Now First it should subset the dataframe with first two rows
 df <- df[1:2,]
 df %>%
 group_by(Blocks) %>%
 summarise(count = n())

Then it should subset the dataframe with next 3 rows
 df <- df[3:5,]
 df %>%
 group_by(Blocks) %>%
 summarise(count = n())

and so on. Desired output will be,
 Subset    2D    2E     4F     5E
  2         1     1     0      0
  3         1     0     1      1
  2         2     0     0      0

Individually I can do with above code,but my dataframe is huge and I have to subset it many times.
How can we do it more effectively in R?            

A:

We can use rep to create a grouping variable for splitting the dataset into a list of 'data.frame', then with map, get the count
library(tidyverse)
split(df, rep(seq_along(vec), vec)) %>% 
              map(~ .x %>%
                      count(Blocks))

Or another option is to create a column of 'grp' based on 'vec' (to be more aligned with the expected output which is 'wide' dataset., along with 'Subset' that is actual values of 'vec', summarise to get the frequency and spread the data to 'wide' format
df %>%
   filter(row_number() <= sum(vec)) %>% #based on the comments from OP
   mutate(Subset = rep(vec, vec)) %>%
   group_by(grp = rep(seq_along(vec), vec), Blocks) %>%
   summarise(Subset = first(Subset), n = n())%>%
   ungroup %>%
   spread(Blocks, n, fill = 0) %>%
   select(-grp)
# A tibble: 3 x 5
#   Subset  `2D`  `2E`  `4F`  `5E`
#*  <dbl> <dbl> <dbl> <dbl> <dbl>
#1   2.00  1.00  1.00  0     0   
#2   3.00  1.00  0     1.00  1.00
#3   2.00  2.00  0     0     0   

