## Dates to weeks -----------------------------------------------------------
# The same set of days will occur in different weeks depending on the start
# date. Here we can define a week before and after today
print(dat <- as.Date("2018-12-31") + -6:7)
# By default, the weeks are defined as ISO weeks, which start on Monday
print(iso_dat <- date2week(dat))
# This can be changed by setting the global default with set_week_start()
set_week_start("Sunday")
date2week(dat)
# If you want lubridate-style numeric-only weeks, you need look no further
# than the "numeric" argument
date2week(dat, numeric = TRUE)
# To aggregate weeks, you can use `floor_day = TRUE`
date2week(dat, floor_day = TRUE)
# If you want aggregations into factors that include missing weeks, use
# `floor_day = TRUE, factor = TRUE`:
date2week(dat[c(1, 14)], floor_day = TRUE, factor = TRUE)
## Weeks to dates -----------------------------------------------------------
# The aweek class can be converted back to a date with `as.Date()`
as.Date(iso_dat)
# If you don't have an aweek class, you can use week2date(). Note that the
# week_start variable is set by the "aweek.week_start" option, which we will
# set to Monday:
set_week_start("Monday")
week2date("2019-W01-1") # 2018-12-31
# This can be overidden by the week_start argument;
week2date("2019-W01-1", week_start = "Sunday") # 2018-12-30
# If you want to convert to the first day of the week, you can use the
# `floor_day` argument
as.Date(iso_dat, floor_day = TRUE)
## The same two week timespan starting on different days --------------------
# ISO week definition: Monday -- 1
date2week(dat, 1)
date2week(dat, "Monday")
# Tuesday -- 2
date2week(dat, 2)
date2week(dat, "Tuesday")
# Wednesday -- 3
date2week(dat, 3)
date2week(dat, "W") # you can use valid abbreviations
# Thursday -- 4
date2week(dat, 4)
date2week(dat, "Thursday")
# Friday -- 5
date2week(dat, 5)
date2week(dat, "Friday")
# Saturday -- 6
date2week(dat, 6)
date2week(dat, "Saturday")
# Epiweek definition: Sunday -- 7
date2week(dat, 7)
date2week(dat, "Sunday")
Run the code above in your browser using DataLab