Get a week starting week and year in R
I'm looking for a function that will get the year + week + day of the week and return the date, for example:
I would like to enter the following 3
2015 Monday 23
And get the desired output:
"2015-06-08"
After searching the web, there seems to be an equivalent question in other languages, but not in R:
How to get date from week number and year
Any help on this would be great!
source to share
There are two caveats here:
-
The result depends on the current locale.
In my locale"German_Germany.1252"
(callSys.getlocale("LC_TIME")
to check your locale)strptime("2015Monday23", "%Y%A%U")
returnsNA
. -
The results depend on the convention for the numbering of the weeks in the year.
There are 3 conventionsR
: US, UK and ISO 8601. See this answer for a detailed discussion. Thus, the convention to be used for the conversion must be specified.
Non-english locales
If you are in a non-English language, you can deal with English names of the days of the week (or names of the months, similarly) by temporarily changing the current language:
Sys.setlocale("LC_TIME", "US") #> [1] "English_United States.1252" strptime("2015Monday23", "%Y%A%U") #> [1] "2015-06-08 CEST" Sys.setlocale("LC_TIME") #> [1] "German_Germany.1252"
The package lubridate
offers a more convenient way:
lubridate::parse_date_time("2015Monday23", "YAU", locale = "US") #> [1] "2015-06-08 UTC"
Week of the year in different agreements
Since the day of the week is determined by its name, the US and UK agreements return the same result:
lubridate::parse_date_time("2015Monday23", "YAU", locale = "US") #> [1] "2015-06-08 UTC" lubridate::parse_date_time("2015Monday23", "YAW", locale = "UK") #> [1] "2015-06-08 UTC"
Unfortunately, the format specifiers for the ISO 8601 convention are not accepted in the input. So we reverse the process and format the final date as the week of the year in different conventions, which shows a great result for ISO 8601.
format(as.Date("2015-06-08 UTC"), "%Y-%W-%u") # UK convention #> [1] "2015-23-1" format(as.Date("2015-06-08 UTC"), "%Y-%U-%w") # US convention #> [1] "2015-23-1" format(as.Date("2015-06-08 UTC"), "%G-%V-%u") # ISO 8601 #> [1] "2015-24-1"
source to share