My goal is to get the previous 3 Mondays in date format 2022-01-31
based off a date.
I know I can use the following to get 1 monday.
So for example today is 2022-11-16 and monday was 2022-11-14
library(lubridate)
todays_date <- as.Date('2022-11-16')
floor_date(todays_date, 'week') 1
I can also do - 6
to get last week monday's but if "today's date" changes then will that also change?
floor_date(todays_date, 'week') - 6
Desired Goal
Date Give = 2022-11-16
- first_monday = 2022-11-14
- second_monday = 2022-11-07
- third_monday = 2022-10-31
- fourth_monday = 2022-10-24
CodePudding user response:
Dates are stored as integers, so just subtract a sequence of 7s to get previous Mondays:
todays_date <- Sys.Date()
lubridate::floor_date(todays_date, 'week') 1 - (0:2) * 7
#> [1] "2022-11-14" "2022-11-07" "2022-10-31"
Here's years' worth of Mondays:
lubridate::floor_date(todays_date, 'week') 1 - (0:52) * 7
#> [1] "2022-11-14" "2022-11-07" "2022-10-31" "2022-10-24" "2022-10-17"
#> [6] "2022-10-10" "2022-10-03" "2022-09-26" "2022-09-19" "2022-09-12"
#> [11] "2022-09-05" "2022-08-29" "2022-08-22" "2022-08-15" "2022-08-08"
#> [16] "2022-08-01" "2022-07-25" "2022-07-18" "2022-07-11" "2022-07-04"
#> [21] "2022-06-27" "2022-06-20" "2022-06-13" "2022-06-06" "2022-05-30"
#> [26] "2022-05-23" "2022-05-16" "2022-05-09" "2022-05-02" "2022-04-25"
#> [31] "2022-04-18" "2022-04-11" "2022-04-04" "2022-03-28" "2022-03-21"
#> [36] "2022-03-14" "2022-03-07" "2022-02-28" "2022-02-21" "2022-02-14"
#> [41] "2022-02-07" "2022-01-31" "2022-01-24" "2022-01-17" "2022-01-10"
#> [46] "2022-01-03" "2021-12-27" "2021-12-20" "2021-12-13" "2021-12-06"
#> [51] "2021-11-29" "2021-11-22" "2021-11-15"
Created on 2022-11-16 with reprex v2.0.2
CodePudding user response:
Using seq.Date
, going back 4 weeks (28 days), starting from today.
today <- as.Date("2022-11-16")
days <- seq.Date(today - 28, today, "day")
days[format(days, "%A") == "Monday"]
[1] "2022-10-24" "2022-10-31" "2022-11-07" "2022-11-14"