# Help on Looping

I'm going to give you the solution, but I want to ask you for something in return, please read and follow this guides before writing your next post/topic

library(tidyverse)
library(lubridate)

data <- data.frame(
Id = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L,
14L, 15L),
nos = c(4L, 2L, 3L, 2L, 3L, 2L, 2L, 3L, 1L, 5L, 2L, 1L, 2L, 1L, 1L),
grade = c(3L, 3L, 3L, 3L, 3L, 2L, 2L, 4L, 4L, 3L, 3L, 4L, 3L, 3L, 4L),
Date_Created = c("2016-03-01", "2016-03-15", "2016-03-21", "2016-05-25",
"2016-07-29", "2016-07-29", "2016-07-29", "2016-08-04",
"2016-10-14", "2016-10-31", "2017-04-13", "2017-04-13",
"2017-04-13", "2017-04-13", "2017-06-29"),
location = as.factor(c("Aus", "Aus", "Aus", "Ind", "Ind", "Ind", "ML",
"ML", "Aus", "Ind", "Ind", "PA", "KA", "LA",
"LA"))
)

data\$Date_Created = ymd(data\$Date_Created)

data %>%
mutate(earliest_date = Date_Created %m-% months(6),
count = pmap_dbl(.l = list(location,
earliest_date,
Date_Created),
~ data %>%
filter(location == ..1, grade == ..2, Date_Created >= ..3 & Date_Created <= ..4) %>%
summarise(count = n()) %>%
.\$count
),
sum_nos = pmap_dbl(.l = list(location,
earliest_date,
Date_Created),
~ data %>%
filter(location == ..1, grade == ..2, Date_Created >= ..3 & Date_Created <= ..4) %>%
summarise(sum_nos = sum(nos)) %>%
.\$sum_nos
)
)
#>    Id nos grade Date_Created location earliest_date count sum_nos
#> 1   1   4     3   2016-03-01      Aus    2015-09-01     1       4
#> 2   2   2     3   2016-03-15      Aus    2015-09-15     2       6
#> 3   3   3     3   2016-03-21      Aus    2015-09-21     3       9
#> 4   4   2     3   2016-05-25      Ind    2015-11-25     1       2
#> 5   5   3     3   2016-07-29      Ind    2016-01-29     2       5
#> 6   6   2     2   2016-07-29      Ind    2016-01-29     1       2
#> 7   7   2     2   2016-07-29       ML    2016-01-29     1       2
#> 8   8   3     4   2016-08-04       ML    2016-02-04     1       3
#> 9   9   1     4   2016-10-14      Aus    2016-04-14     1       1
#> 10 10   5     3   2016-10-31      Ind    2016-04-30     3      10
#> 11 11   2     3   2017-04-13      Ind    2016-10-13     2       7
#> 12 12   1     4   2017-04-13       PA    2016-10-13     1       1
#> 13 13   2     3   2017-04-13       KA    2016-10-13     1       2
#> 14 14   1     3   2017-04-13       LA    2016-10-13     1       1
#> 15 15   1     4   2017-06-29       LA    2016-12-29     1       1
2 Likes