Adding weeks by taking year ending weeks into account

# vector of 53-week year
year53 <- c(2020, 2026) 

# toy data
df <- tibble(
  year_zero_week = c(2020052, 2020053, 2021051, 2026052)
)

df
#> # A tibble: 4 x 1
#>   year_zero_week
#>            <dbl>
#> 1        2020052
#> 2        2020053
#> 3        2021051
#> 4        2026052

I want to be able to add weeks to df's column such that the new column values do not exceed 52(or 53). In the following example, I added 2 weeks. In the first row, for example, since the year 2020 is 53-year weeks, so adding 2 weeks to 2020052 becomes 2021001. How can I achieve it?

# A tibble: 4 x 2
  year_zero_week year_zero_week_wanted
           <dbl>                 <dbl>
1        2020052               2021001
2        2020053               2021002
3        2021051               2022001
4        2026052               2027001
library(tidyverse)
library(ISOweek)

df <- tibble(
  year_zero_week = c(
    2020052,
    2020053,
    2021051,
    2026052
  )
)

(df_full <- mutate(df,
  year_zero_week_chr = as.character(year_zero_week),
  year_week_char = paste0(
    substr(year_zero_week_chr, 1, 4),
    "-W",
    substr(year_zero_week_chr, 6, 7),
    "-1"
  ), # assume we want day 1 of the week,
  year_week_date = ISOweek2date(year_week_char),
  year_week_plus_2w = (\(x) {
    w1 <- week(x)
    week(x) <- w1 + 2
    x
  })(year_week_date),
  year_week_plus_2w_num = 1000 * year(year_week_plus_2w) + week(year_week_plus_2w)
))

(df_res <- df_full |> select(
  year_zero_week, year_zero_week_wanted = year_week_plus_2w_num
))

Many thanks for teaching me some new tricks :slight_smile:

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.