Search code examples
ras.date

Transform a "Year-ISO Week" character object to a Date object


I've been having some struggles with dates. Namely, being able recognize a variable (as a Datevariable) that has dates registered by the following manner: Year-ISO week. So the following code:

class("2021-20")

Idealy should return: Date .

The following code recognizes it as a date, but it returns a date that I don't understand where it comes from. And even if I try with other dates (different values of the ISO week), I always get the same response:

as.Date("2021-20", format = "%Y-%W")
[1] "2021-12-13"

I've tried transforming "normal dates" to the format year-iso week, but it leads to no where, I can never get it to be recognized as a Dateobject, and I need to perform ggplot2graphs.

This question was linked to this one, although the question itself is very similar, I am still not able to get the result I desire.


Solution

  • As you noted in the comments, R has a Date format that is always YYYY-MM-DD, so if you want to plot data with a date axis, it often makes sense to convert your format to that. But there's nothing preventing you from subsequently formatting the Date data to display with an arbitrary other format. This will change the display appearance on the axis after the physical position mapping has occurred using the Date data.

    So you can plot year-week data, but you have to take a detour to Date and then come back. As noted in related questions, year-weeks include 7 days, so to convert a year-week to a Date you need to specify which day of the week to use; that's the "1" in the paste part.

    In the example data below, I've added gaps so you can see how the Date data is mapped correctly to the timeline.

    data.frame(year = c(rep(2021,8), rep(2022, 3)),
               week = c(45:52, 1, 3, 5),
               val = 1:11) |>
    
      ggplot(aes(x = as.Date(paste(year, week, 1, sep = "-"), "%Y-%W-%w"),
                 y = val)) +
      geom_point() +
      scale_x_date(date_breaks = "week", date_labels = "%Y-%W", name = "year-week")
    

    enter image description here