Here is a solution with two differences from your request.
- The Group labels are simply numbers, not the text you show.
- When the grouping_value is 7, the groups have 7 days. In your example, a value of 7 leads to groups of 8 days, e.g. Jan. 1 - Jan. 8. Is that really what you want?
I did not drop the DateDelta column because I think it is easier to see how the groups are formed if that is present. It can easily be dropped.
library(tidyverse)
#> Warning: package 'tibble' was built under R version 4.1.2
library(lubridate)
#>
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#>
#> date, intersect, setdiff, union
StartDay <- ymd("2022-01-01")
EndDay <- ymd("2022-02-10")
DF <- data.frame(Date = seq.Date(from = StartDay,
to = EndDay, by = 5))
DF
#> Date
#> 1 2022-01-01
#> 2 2022-01-06
#> 3 2022-01-11
#> 4 2022-01-16
#> 5 2022-01-21
#> 6 2022-01-26
#> 7 2022-01-31
#> 8 2022-02-05
#> 9 2022-02-10
GroupFunc <- function(DAT, GrpVal) {
DAT <- DAT |> mutate(DateDelta = as.numeric(Date - min(Date)),
Group = DateDelta %/% GrpVal)
}
NewDF <- GroupFunc(DF, 7)
NewDF
#> Date DateDelta Group
#> 1 2022-01-01 0 0
#> 2 2022-01-06 5 0
#> 3 2022-01-11 10 1
#> 4 2022-01-16 15 2
#> 5 2022-01-21 20 2
#> 6 2022-01-26 25 3
#> 7 2022-01-31 30 4
#> 8 2022-02-05 35 5
#> 9 2022-02-10 40 5
Created on 2022-03-08 by the reprex package (v2.0.1)