Search code examples
rtidyverselubridateas.date

How to convert week numbers into date format using R


I am trying to convert a column in my dataset that contains week numbers into weekly Dates. I was trying to use the lubridate package but could not find a solution. The dataset looks like the one below:

df <- tibble(week = c("202009", "202010", "202011","202012", "202013", "202014"),
             Revenue = c(4543, 6764, 2324, 5674, 2232, 2323))

So I would like to create a Date column with in a weekly format e.g. (2020-03-07, 2020-03-14).

Would anyone know how to convert these week numbers into weekly dates?


Solution

  • Maybe there is a more automated way, but try something like this. I think this gets the right days, I looked at a 2020 calendar and counted. But if something is off, its a matter of playing with the (week - 1) * 7 - 1 component to return what you want.

    This just grabs the first day of the year, adds x weeks worth of days, and then uses ceiling_date() to find the next Sunday.

    library(dplyr)
    library(tidyr)
    library(lubridate)
    
    df %>% 
      separate(week, c("year", "week"), sep = 4, convert = TRUE) %>% 
      mutate(date = ceiling_date(ymd(paste(year, "01", "01", sep = "-")) + 
                                   (week - 1) * 7 - 1, "week", week_start = 7))
    
    # # A tibble: 6 x 4
    #    year  week Revenue date      
    #   <int> <int>   <dbl> <date>    
    # 1  2020     9    4543 2020-03-01
    # 2  2020    10    6764 2020-03-08
    # 3  2020    11    2324 2020-03-15
    # 4  2020    12    5674 2020-03-22
    # 5  2020    13    2232 2020-03-29
    # 6  2020    14    2323 2020-04-05