1

I work with the package lubridate and am a little bit confused because Friday, January 29 and Monday, February, 2 belong to the same week, which doesn't make sense. Here my code:

library(lubridate)
day1 <- "2021-01-29 00:03:43 CET"
day5 <- "2021-02-01 08:28:51 CET"
week(day1)
wday(day1, label = T)
week(day5)
wday(day5, label = T)

This gives me the following output

> week(day1)
[1] 5
> wday(day1, label = T)
[1] Fr\\.
Levels: So\\. < Mo\\. < Di\\. < Mi\\. < Do\\. < Fr\\. < Sa\\.
> week(day5)
[1] 5
> wday(day5, label = T)
[1] Mo\\.
Levels: So\\. < Mo\\. < Di\\. < Mi\\. < Do\\. < Fr\\. < Sa\\.

Another weird thing is the levels of the days. Any idea what is wrong here. I just updated all my packages.

Cheers Renger

phiver
  • 23,048
  • 14
  • 44
  • 56
arnyeinstein
  • 669
  • 1
  • 5
  • 14
  • 1
    ?week() : week() returns the number of complete seven day periods that have occurred between the date and January 1st, plus one. – Waldi Feb 01 '21 at 12:58
  • 1
    The levels of the days are correct. It is an ordered factor starting on Sunday. You can adjust this by setting the option `week_start`, like `wday(day5, label = T, week_start = 1)` to have the week start on a Monday. Also use `isoweek` to get the weeknumbers according to the iso standards. – phiver Feb 01 '21 at 13:03
  • 1
    Relevant post on week conventions: [Transform year/week to date object](https://stackoverflow.com/questions/45549449/transform-year-week-to-date-object/45587644#45587644). – Henrik Feb 01 '21 at 14:58
  • Thanks to all! What about the weird levels for the days So\\. < Mo\\. ? – arnyeinstein Feb 02 '21 at 07:17
  • see https://github.com/tidyverse/lubridate/issues/551. US weeks start on sunday, European on Monday, you can set this using `week_start` argument, see the edit in my answer – Waldi Feb 03 '21 at 17:22

2 Answers2

2

You could use isoweek():

> isoweek(day1)
[1] 4
> isoweek(day5)
[1] 5

Regarding starting day of week, you can set it in wday with week_start argument :

wday(day1, label = T, week_start = getOption("lubridate.week.start", 1))
Waldi
  • 39,242
  • 6
  • 30
  • 78
2

According to its help file, the week() function "returns the number of complete seven day periods that have occurred between the date and January 1st, plus one."

Thus, the behavior of Friday, January 29, and Monday, February 2, is expected. They are both part of the fifth seven-day period of 2021.

Week  Dates
1     Jan 1 - Jan 7
2     Jan 8 - Jan 14
3     Jan 15 - Jan 21
4     Jan 22 - Jan 28
5     Jan 29 - Feb 4

As for your week days, the wday() function has a locale argument. By default it is set to locale = Sys.getlocale("LC_TIME"), which is current system locale. The wday() function then returns day name abbreviations based on that locale. Use Sys.getlocale("LC_TIME") to see your current locale. If it is not what you expect, you can change your locale: How to change the locale of R?.

Ben Norris
  • 5,639
  • 2
  • 6
  • 15