1

I have data in a specifc format year_isoweek, e.g., 2019_31 for this week. And I want this represented as a date for further processing.

basic r and lubridate;
I found some work arounds that have merit, but none of these work with ISO 8601 (%V) which leads to other problems in turn:
convert year week string to date
Convert week number to date
Transform year/week to date object

a <- c("2019_7", "2019_3", "2018_18")
as.Date(a, "%Y_%V")

Actual output:

[1] "2019-07-31" "2019-07-31" "2018-07-31"

What I want: "2019-02-11" "2019-01-14" "2018-04-30" as class date

Markus
  • 169
  • 1
  • 9
  • 1
    Maybe `strptime(paste0(a, -1), "%Y_%W-%w")`? – Matt Jul 31 '19 at 16:07
  • @Matt I tried this: `a <- c("2019-7", "2019-3", "2018-18")` `b <- strptime(paste0(a, -1), "%Y-%W-%w")` `str(b)` `POSIXlt[1:3], format: "2019-02-18" "2019-01-21" "2018-04-30"` That is not close enough for my purposes. Dates must be within the corresponding ISO 8601 week. (sry, I do not get Line Breaks to work) – Markus Aug 01 '19 at 07:52

1 Answers1

0

Okay, I found a solution using the package ISOweek:

library(ISOweek)
library(stringr)
a <- c("2019", "2019", "2018")
b <- str_pad(c("7", "3", "18"), 2, pad = "0")
c <- ISOweek2date(paste0(a,"-W",b, "-",1))
str(c)

Date[1:3], format: "2019-02-11" "2019-01-14" "2018-04-30"
is exactly as
"2019-02-11" "2019-01-14" "2018-04-30" as class date as I wanted!

There is an inconvenience with ISOweek because it does not accept single digits or single char strings as week numbers (e.g., "7" is not accepted, only "07" is). Therefore, stringr package is needed, too.

Markus
  • 169
  • 1
  • 9