Data
I'm working with the following data from 2019 to 2022
library(tidyverse)
library(lubridate)
set.seed(123)
df <-
tibble(
date = sample(
seq(as.Date('2019/01/01'), as.Date('2022/09/01'), by = "day"),
size = 100,
replace = T))
Desired output
I would like to create a new variable that summarises each week into the same month-day range across 2019-2022. The result should be the week staring the same month-day regardless of what weekday or week of the year that date happens to be each year.
For example
- 2019-07-03 should become "July 01" (Short for "Week starting July 01)
- 2021-07-03 should become "July 01" (New year, same month-day)
- 2021-07-04 should become "July 01"
- 2021-07-05 should become "July 01"
- 2021-07-06 should become "July 01"
- 2021-07-07 should become "July 01"
- 2021-07-08 should become "July 08" (New week has started, increment the month-day by 7)
- 2021-07-14 should become "July 08"
- 2021-07-15 should become "July 15" (New week has started, increment the month-day by 7)
- 2021-07-16 should become "July 15"
- 2022-07-15 should become "July 15" (New year, same month-day)
- Etc.
Failed attempt
I've tried using cat.Date() and lubridate::floor_date() but these return the floor date for that particular year. For example
df %>%
mutate(
date_month_week = lubridate::floor_date(date, unit = "week", week_start = 7),
date_month_week = format(as.Date(date_month_week), "%m-%d")) %>%
arrange(desc(date_month_week)) %>%
distinct(date_month_week)
Yields
# A tibble: 77 × 1
date_month_week
<chr>
1 12-20
2 12-15
3 12-12
4 12-08
5 12-06
6 12-01
7 11-28
8 11-24
9 11-22
10 11-21
Many thanks for your help.