0

I have a date in the follow format (year and week number):

year_week
201804
201938
201745
201402
201510

I need to get the full date in such format: 2018-02-26 (%Y-%m-%d). I use the next code for this purpose:

dt[, full_date := format(ISOweek2date(sub("(\\d{4})(\\d{2})", "\\1-W\\2-1", year_week)),"%Y-%m-%d")]

but, I have the following error:

"Error: all(is.na(weekdate) | stringr::str_detect(weekdate, kPattern)) is not TRUE"

How can I get the full date in another way? Why am I having this error?

Thanks a lot for any help!

P.S. Sunday or Monday can be used as the first day of week.

Hilary
  • 475
  • 3
  • 10

1 Answers1

4

You can add a weekday to the date and use

as.Date(paste0(df$year_week, 1),"%Y%U%u")
#[1] "2018-01-29" "2019-09-23" "2017-11-06" "2014-01-13" "2015-03-09"

data

df <- structure(list(year_week = c(201804L, 201938L, 201745L, 201402L, 
201510L)), class = "data.frame", row.names = c(NA, -5L))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213