Convert week number to date
Another option with lubridate
lubridate::parse_date_time(paste(2014, df$Week, 1, sep="/"),'Y/W/w')
W - week number, w - weekday number, 0-6 (Sun-Sat)
Another alternative is to make sure that week numbers have two digits, which can be done using stringr::str_pad()
, which will add a pad="0"
to make sure there are width=2
digits:
year <- 2015
week <- 1
as.Date(paste(year, week, "1", sep=""), "%Y%U%u")
#> [1] NA
as.Date(paste(year, stringr::str_pad(week,width=2, pad="0"), "1", sep=""), "%Y%U%u")
#> [1] "2015-01-05"
as.Date(paste(year, week, "1", sep="-"), "%Y-%U-%u")
#> [1] "2015-01-05"
Created on 2021-04-19 by the reprex package (v1.0.0)
An alternative solution is to use date arithmetic from the lubridate
package:
lubridate::ymd( "2014-01-01" ) + lubridate::weeks( df$Week - 1 )
The -1
is necessary because 2014-01-01
is already week 1. In other words, we want:
df$Week == 1
to map to2014-01-01
(which isymd("2014-01-01") + weeks(1-1)
)df$Week == 2
to map to2014-01-08
(which isymd("2014-01-01") + weeks(2-1)
)- and so on.
as.Date
is calling the 1 to 9 as NA as it is expects two digits for the week number and can't properly parse it.
To fix it, add in some - to split things up:
as.Date(paste(2014, df$Week, 1, sep="-"), "%Y-%U-%u")