I have a period that I want to divide into weeks from Monday to Sunday.
Using lubridate
, I can query the week number of a date:
library(lubridate)
td = today()
week(td) #48
How could I find all the days that belong to the 48th week of, say, 2020?
You can use seq
and as.Date
, where %Y
is the year, %W
Week of the year and %a
Abbreviated weekday.
seq(as.Date("2020-48-Mo", "%Y-%W-%a"), by=1, length.out=7)
#as.Date("2020-48-Mo", "%Y-%W-%a") + 0:6 #Alternative
#as.Date("2020-48-1", "%Y-%W-%u") + 0:6 #Alternative
#[1] "2020-11-30" "2020-12-01" "2020-12-02" "2020-12-03" "2020-12-04"
#[6] "2020-12-05" "2020-12-06"
Use %U
in case Sunday is the first day and %W
with Monday and having the weeks starting with 0
. Use %V
with Monday as the first day and weeks starting with 1
.
In case you have a Date and want all days of this week:
x <- as.Date("2020-11-25")
x - as.integer(format(x, "%u")) + 1:7
#[1] "2020-11-23" "2020-11-24" "2020-11-25" "2020-11-26" "2020-11-27"
#[6] "2020-11-28" "2020-11-29"