4

I have been following along with Hadley Wickham's R for data science book. He has a lot of advice on using lubridate, but a lot of the functions assume that you have year, month, and day. How do you convert to date format when all you have is year and week using lubridate?

data.frame(
    year = c(2015, 2015, 2016, 2016, 2016, 2016, 2016),
    week = c(1, 20, 35, 49, 8, 4, 53)
  )

#year   week
#2015    1
#2015    20
#2016   35  
#2016   49  
#2016   8   
#2016   4   
#2016   53
Andrew Brēza
  • 7,705
  • 3
  • 34
  • 40
Alex
  • 2,603
  • 4
  • 40
  • 73

2 Answers2

7

You can do this with the weeks() function in lubridate, if you want. You just have to first set up a baseline date object. I did that here using str_c from stringr.

library(dplyr)
library(stringr)

my_dates <- tribble(
    ~year,   ~week,
    2015,    1,
    2015,    20,
    2016,    35,  
    2016,    49,  
    2016,    8,  
    2016,    4,   
    2016,    53
)

my_dates %>%
    mutate(beginning = ymd(str_c(year, "-01-01")),
           final_date = beginning + weeks(week))
#> # A tibble: 7 x 4
#>    year  week  beginning final_date
#>   <dbl> <dbl>     <date>     <date>
#> 1  2015     1 2015-01-01 2015-01-08
#> 2  2015    20 2015-01-01 2015-05-21
#> 3  2016    35 2016-01-01 2016-09-02
#> 4  2016    49 2016-01-01 2016-12-09
#> 5  2016     8 2016-01-01 2016-02-26
#> 6  2016     4 2016-01-01 2016-01-29
#> 7  2016    53 2016-01-01 2017-01-06
Julia Silge
  • 10,848
  • 2
  • 40
  • 48
3

Arkun's answer is tidy and accurate but since you asked about using lubridate I figured I'd add my two cents. You want to define New Year's day for each year in question and then advance the specified number of weeks from that. This makes it much easier to account for leap years (which stymied my first effort to answer this question).

library(tidyverse)
library(lubridate)

date_week <- data.frame(
  year = c(2015, 2015, 2016, 2016, 2016, 2016, 2016, 1970),
  week = c(1, 20, 35, 49, 8, 4, 53, 1)
)

date_week %>%
  tbl_df() %>% 
  mutate(newyears = ymd(paste0(year,"-01-01"))) %>% 
  mutate(date = newyears + weeks(week))
Andrew Brēza
  • 7,705
  • 3
  • 34
  • 40
  • As an aside, this is the solution that would have worked if it weren't for those frustrating leap years: `mutate(date = as_date(((year - 1970) * 365) + (week * 7) - 1))` – Andrew Brēza Jul 28 '17 at 03:13