I have a DateTime series (see below as an example). I have to assign groups to these dates based on 8 days intervals. Basically, the group should be assigned as per the following rules (for any given year): - Group 1: (Jan 1 - Jan 8); Group 2: (Jan 9 - Jan 16); and so on. So, basically, there will be 46 groups (~(365 or 366)/8) in total in a year. The last group in a year will have only either 5 days or 6 days (365 or 366 - 45*8). What is a convenient way to approach this?
x <- as.POSIXct("2021-12-31") as.difftime(c(1:10,50,100,350,364,470), units="days")
CodePudding user response:
Using cut
with a sequence of 8 day blocks, compared to the Julian days extracted from each date object.
Example data:
x <- as.POSIXct("2021-12-31") as.difftime(c(1:10,50,100,350,364,470), units="days")
Cut and review results:
grp <- cut(as.integer(format(x, "%j")), breaks=c(seq(0,366,8), 366))
data.frame(x, grp)
# x grp
#1 2022-01-01 (0,8]
#2 2022-01-02 (0,8]
#3 2022-01-03 (0,8]
#4 2022-01-04 (0,8]
#5 2022-01-05 (0,8]
#6 2022-01-06 (0,8]
#7 2022-01-07 (0,8]
#8 2022-01-08 (0,8]
#9 2022-01-09 (8,16]
#10 2022-01-10 (8,16]
#11 2022-02-19 (48,56]
#12 2022-04-10 (96,104]
#13 2022-12-16 (344,352]
#14 2022-12-30 (360,366]
#15 2023-04-15 (104,112]