Epo Luusk
Epo Luusk

Reputation: 37

How to convert YearWeek format to date?

My data: c("202001", "202002").

It shows Year and the number of the week. I need to get the first day of the week added to my data.

How can I get it?

Desired output: 2020-01-06 and 2020-01-13.

Original data, for which the code should work

c(
"202001", "202002", "202003", "202004", "202005", "202006", "202007", 
"202008", "202009", "202010", "202011", "202012", "202013", "202014", 
"202015", "202016", "202017", "202018", "202019", "202020", "202021", 
"202022", "202023", "202024", "202025", "202026", "202027", "202028", 
"202029", "202030", "202031", "202032", "202033", "202034", "202035", 
"202036", "202037", "202038", "202039", "202040", "202041", "202042", 
"202043", "202044", "202045", "202046", "202047", "202048", "202049", 
"202050", "202051", "202052", "202053", "202101", "202102", "202103")```

Upvotes: 0

Views: 948

Answers (2)

jomcgi
jomcgi

Reputation: 106

You can do this with base-r using as.Date and specifying the format.

Week of the year

  • US convention: Week of the year as decimal number (00–53) using Sunday as the first day 1 of the week (and typically with the first Sunday of the year as day 1 of week 1): %U

  • UK convention: Week of the year as decimal number (00–53) using Monday as the first day of week (and typically with the first Monday of the year as day 1 of week 1): %W

  • ISO 8601 definition: Week of the year as decimal number (01–53) as defined in ISO 8601. If the week (starting on Monday) containing 1 January has four or more days in the new year, then it is considered week 1. Otherwise, it is the last week of the previous year, and the next week is week 1: %V which is accepted but ignored on input.
    Note that there is also a week-based year (%G and %g) which is to be used with %V as it may differ from the calendar year (%Y and %y).

Numeric weekday

  • Weekday as a decimal number (1–7, Monday is 1): %u
  • Weekday as decimal number (0–6, Sunday is 0): %w

I append 1 to create a date string referencing the first day of the year-week and then specify the format using strptime codes when calling as.date to convert it.

Example with US convention:

dateList <-  c("202001", "202002")

dateList <- paste0(dateList, "1")

dateList <- as.Date(dateList , format = "%Y%W%u")

More information on the formats is available here: https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/strptime

Upvotes: 2

AlexB
AlexB

Reputation: 3269

One way would be to use lubridate package like this:

c("202001", "202002") -> x    
lubridate::ymd('2019-12-30') + lubridate::weeks(as.numeric(substr(x, 5, 6)))

#"2020-01-06" "2020-01-13"

Upvotes: 0

Related Questions