ISO week to date

week_iso date_start date_end
2022024 20220613 20220619
2022025 20220620 20220626

Given iso week, week_iso, how can I mutate date-variables which represent the start and end dates of a given week?

library(tidyverse)
library(lubridate)

# toy data
df <- tibble(week_iso = c("2022024", "2022025"))
df
#> # A tibble: 2 x 1
#>   week_iso
#>   <chr>   
#> 1 2022024 
#> 2 2022025

You can use the ISOweek package with a little trick

library(dplyr)
library(stringr)
library(ISOweek)

df <- data.frame(week_iso = c("2022024", "2022025"))

df %>% 
    mutate(date_start = ISOweek2date(paste0(str_replace(week_iso, "(?<=2022)0", "-W"), "-1")),
           date_end = ISOweek2date(paste0(str_replace(week_iso, "(?<=2022)0", "-W"), "-7")))
#>   week_iso date_start   date_end
#> 1  2022024 2022-06-13 2022-06-19
#> 2  2022025 2022-06-20 2022-06-26

Created on 2022-06-19 by the reprex package (v2.0.1)

1 Like

In addition to the solution by @andresrcs, you could also use the clock package, which has a built in type for ISO year-week. I haven't added a direct parser for that yet, but you can use stringr here too to work around that:

library(dplyr)
library(stringr)
library(clock)

df <- data.frame(week_iso = c("2022024", "2022025"))
df
#>   week_iso
#> 1  2022024
#> 2  2022025

df <- df %>% 
  mutate(
    year = as.integer(str_sub(week_iso, end = 4)),
    week = as.integer(str_sub(week_iso, start = 5)),
    yw = iso_year_week_day(year, week),
    start = set_day(yw, 1),
    end = set_day(yw, 7)
  ) 
df
#>   week_iso year week       yw      start        end
#> 1  2022024 2022   24 2022-W24 2022-W24-1 2022-W24-7
#> 2  2022025 2022   25 2022-W25 2022-W25-1 2022-W25-7

df %>%
  mutate(start = as.Date(start), end = as.Date(end))
#>   week_iso year week       yw      start        end
#> 1  2022024 2022   24 2022-W24 2022-06-13 2022-06-19
#> 2  2022025 2022   25 2022-W25 2022-06-20 2022-06-26

Created on 2022-06-19 by the reprex package (v2.0.1)

1 Like

Thank you both for your solutions. I find them very helpful. Thanks again!

@andresrcs How will your code change if we work with different year-week data? For example, consider df <- data.frame(week_iso = c("2021024", "2022025"))

You have to adjust the regular expression to fit your actual data, maybe something like this "(?<=^\\d{4})0"

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.