1

In R, I have a dataset with the week number and the year (see below) and I want to transform it into the date the corresponding Monday of the week.I used the as.Date() function. This works well, except for the first week, where the function return NA as the corresponding Monday of the first week belongs to the previous year. I thus want that the function returns the date of Monday, even if it is not the same year. Any idea?

data.frame(week = paste(2022,0:5,sep="-")) %>%
mutate(week2 = paste(week,"1",sep="-"),
        date=as.Date(week2, "%Y-%W-%w"))
week    week2       date
1 2022-0 2022-0-1       <NA>
2 2022-1 2022-1-1 2022-01-03
3 2022-2 2022-2-1 2022-01-10
4 2022-3 2022-3-1 2022-01-17
5 2022-4 2022-4-1 2022-01-24
6 2022-5 2022-5-1 2022-01-31
Anthony
  • 377
  • 2
  • 6
  • 13
  • Does this answer your question? [Transform year/week to date object](https://stackoverflow.com/questions/45549449/transform-year-week-to-date-object) – Merijn van Tilborg Jan 27 '22 at 10:50

1 Answers1

2

Your code is good. But you have only one problem: NA if week == 0. If week number is zero then first day of the year is not monday. So you can check if week number is zero (and find monday in previous year) or do as in you example. For example as.Date("2018-1-1", "%Y-%W-%w") == 2018-01-01 (week == 1, not 0).

foo <- function(year, week) {
    if (week == 0) {
        year <- year - 1
        week <- data.table::week(as.Date(paste0(year, "-12-31"))) - 1
    }
    return(as.Date(paste0(c(year, week, "1"), collapse = "-"), "%Y-%W-%w"))
}