Isocalenderweek/year out of date to create a timeseries

Hello, everyone,

I have to make a time series on iso-calendar weeks. My data are given on a daily basis. I want to aggregate them on ISO calendar week level over the respective product groups. However, I want to have the calendar week and the year in the data and format this as date or POSIXct so that I can create a time series afterwards.
Summarized:
Date (d-m-y) -> Isoweek/year as a new column but formated as.date --> Create time series (frequency 52) per product group (both individually and one large one for all)

My previous attempts have not worked:
data2 <- data %>%
mutate(new_date=as.Date(KW, format="%W"), new_date2=year(Date))

data3 <- data %>%
mutate(new_date=isoweek(date), new_date2=year(date))

Thank you very much for your help.
Enclosed you will find an excerpt from my data so that you can understand the structure.

Kind regards,
Lukas

lubridate::isoweek() returns the week as it would appear in the ISO 8601 system, which uses a reoccurring leap week.

Approach

your_data %>% mutate(iso_week = lubridate::isoweek(lubridate::dmy(Date)) -> output

Thank you for your fast reply.
But if I take your approach I get:
All formats failed to parse. No formats found.

And there are no values in the data (NA).

See the help for lubridate.

dmy(15/07/2020)
ymd(2020-07-15)

and variations are available.

Fixed it thanks.
But it still only gives me the isoweek. It needs to include the year of the week as well. And its format is still num whereas I need date or POSIXct to make a ts() out of it. I am sorry about that many questions. Do you have a solution for that as well?

Two issues then:

  1. Trivially: extract isoweek and year from the datetime object and convert to a string
  2. Possibly infeasible: converting that string to a datetime object

Is 2 required given 1?

It actually is cause I need to make a ts() out of this in the end.

No worries, then. ts doesn't care. You just give it an argument for the start and frequency.

well it doesnt give me a two digit isoweek :confused:

isoweek returns class num To left pad to make two-digit character strings:

date_string <- "2020-07-15"
date_object <- lubridate::ymd(date_string)
lubridate::isoweek(date_string)
#> [1] 29
date_string <- "2020-01-15"
date_object <- lubridate::ymd(date_string)
lubridate::isoweek(date_string)
#> [1] 3
stringr::str_pad(lubridate::isoweek(date_string),2,side = "left", pad = "0")
#> [1] "03"

Created on 2020-07-15 by the reprex package (v0.3.0)

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.