0

I have in my data set a year with calendar week (CW), which needs to be converted to date. Unfortunately I didn't find the right function in lubridate package. It is easy to convert a date to CW but not vice versa.

I also tried the following:

as.Date(x="2019_2", format="%Y_%U")
[1] "2019-02-05"
as.Date(x="2019_2", format="%Y_%W")
[1] "2019-02-05"

Any idea how to deal with this?

Thanks in advance!

Irina
  • 29
  • 5
  • That's odd. `"%V"` says (in [`?strptime`](https://stat.ethz.ch/R-manual/R-devel/library/base/html/strptime.html)) that it is *"Accepted but ignored on input"*, while the other two week-based `%`-codes do not say that ... but they are all incorrect. I wonder if that's a documentation-bug. – r2evans Feb 05 '21 at 21:14
  • I think @borderline_coder's answer has the gist: paste a `1` (Monday) or which day you want to start each week in your standard, and add `%u` to the format. Still odd. – r2evans Feb 05 '21 at 21:22

2 Answers2

2

Try this: as.Date(paste(2019, 2, 1, sep="-"), "%Y-%U-%u")

> as.Date(paste(2019, 2, 1, sep="-"), "%Y-%U-%u")
[1] "2019-01-14"

If you want to refer to x, you can also use:

x = "2019_2"

> as.Date(paste((substring(x, 1, 4)), (sub(".*_(.*)", "\\1\\", x)), 1, sep="-"), "%Y-%U-%u")
[1] "2019-01-14"
borderline_coder
  • 183
  • 1
  • 13
  • 1
    You're onto something, but I think you can simplify it. `as.Date(paste("2019_2", 1), "%Y_%U %u")`. The operating presumption I have is that the string is not broken into individual components and for your first code block, and does not need to be broken down. – r2evans Feb 05 '21 at 21:20
  • The only thing remaining is whether the OP is intending calendar-weeks to be Monday-based (US) or Sunday-based (UK) or "week with the most days in the new year" (ISO). – r2evans Feb 05 '21 at 21:22
0

Use lubridate::weeks() to get the start date of the week you have.

week <- "2019_2"
date <- lubridate::ymd("2019-01-01") + lubridate::weeks(as.numeric(stringr::str_extract(week, pattern = "\\d$")) - 1)
date
    [1] "2019-01-08"
Taufi
  • 1,557
  • 8
  • 14