Yearweek is parsed wrongly in R

Viewed 107

Problem: I am facing the problem that R parses a date (30 December 2019) into yearweek wrongly (Output: 2019 W01). I do not know why this is happening. Any suggestions what to change/alternative way of coding?

format(lubridate::ymd("2019-12-30"), "%Y W%V")
# Output
# 2019 W01

# Desired Output:
# 2019 W52
2 Answers

From the strptime documentation:

%U
    Week of the year as decimal number (00–53) using Sunday as the first day 1 of the 
    week (and typically with the first Sunday of the year as day 1 of week 1). The US
    convention.

%V
    Week of the year as decimal number (01–53) as defined in ISO 8601. If the week
    (starting on Monday) containing 1 January has four or more days in the new year,
    then it is considered week 1. Otherwise, it is the last week of the previous year, 
    and the next week is week 1. (Accepted but ignored on input.)

%W
    Week of the year as decimal number (00–53) using Monday as the first day of week
    (and typically with the first Monday of the year as day 1 of week 1). The UK 
    convention.

It sounds like you may want either %U or %W, depending on whether you want to treat Sunday or Monday as the start of the week.

Note however that these can result in values between 00 and 53, which is a consequence of fixing the start of the week to a particular weekday (either Sunday or Monday). Doing that means that there can actually be a partial week at the start and at the end of the year.

If you prefer to count based on week number 1 beginning on the first day of the year, you can use the function lubridate::week.

For example:

library(lubridate)
year_week <- function(date) paste0(year(date), ' W', week(date))

year_week(ymd("2019-01-01"))
# Result: "2019 W1"

year_week(ymd("2019-12-30"))
# Result: "2019 W52"
Related