tidyverse / lubridate

Make working with dates in R just that little bit easier
https://lubridate.tidyverse.org
GNU General Public License v3.0
728 stars 207 forks source link

`week_start` parameter for `week`? #1108

Closed shaenzi closed 1 year ago

shaenzi commented 1 year ago

I have been puzzling about the different behaviours of wday, which has a week_start parameter, and week, which does not.

So if I check the week and the weekday of a Sunday, this is what I get with the default options:

library(lubridate)
week(as_date("2023-01-29")) # results in 5

wday(as_date("2023-01-29")) # results in 1

When I change the option to start the week on Monday, this only affects the weekday, which then changes, but not the week of a Sunday:

# change the week start to Monday from the default Sunday
options("lubridate.week.start" = 1)

week(as_date("2023-01-29")) # still 5

wday(as_date("2023-01-29")) # now 7

Would it be possible to add a week_start parameter to the week function as well? To me it is counter-intuitive that one is affected and the other is not.

vspinu commented 1 year ago

week does not compute the calendar week (see the code, or the docs). I think you need isoweek or epiweek:

> x <- ymd(c("2023-01-29", "2023-01-30"))
> wday(x, label = T)
[1] Sun Mon
Levels: Sun < Mon < Tue < Wed < Thu < Fri < Sat
> isoweek(x)
[1] 4 5
> epiweek(x)
[1] 5 5
shaenzi commented 1 year ago

Sure, I am in fact using the isoweek for when I want to start my week on Mondays. I am just wondering that I can have wday start e.g. on Wednesday but that is not possible for week

vspinu commented 1 year ago

e.g. on Wednesday but that is not possible for week

This would be like isoweek but on wednesday. The computation of weeks is very simple, count weeks from January 1st. So it's not clear how could that algorithm be adapted to start on a weekday without going into isoweek or epiweek logic. If we are going in this direction it would make more sense to add an argument to isoweek but the use case is rather marginal. How many time one needs to start a week on wednesday?