Get date for first day of week from year-week number at beginning of year

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Get date for first day of week from year-week number at beginning of year



I know I can convert a year-week number to a date with the following


week = "2018-23"
as.Date(paste(week, "1", sep = "-"), '%Y-%W-%u')
[1] "2018-06-04"



However, if I am looking near the beginning of the year such January 1st of 2014 I will get an NA.


NA


week = "2014-00"
as.Date(paste(week, "1", sep = "-"), '%Y-%W-%u')
[1] NA



I realize this is because there is no 'day 1' for that week as January 1st, 2014 landed on a Wednesday so I would need to change the day number for it to work but it still doesn't return the date I want.


as.Date(paste(week, "3", sep = "-"), '%Y-%W-%u')
[1] '2014-01-01'



I want to get the first date for the full week, namely for it to return `2013-12-30'. Is there any way I can accomplish this as I have many years of data that this instance comes up that I would like to avoid manually editing.



I imagine something with lubridate::floor_date but I don't always know what the day number should be.


lubridate::floor_date




1 Answer
1



I am unable to replicate your NA.


NA



When I run your example with week set to 0 or 1, I get this:


as.Date("2014-00-1", "%Y-%W-%u")
[1] "2014-01-06"
as.Date("2014-01-1", "%Y-%W-%u")
[1] "2014-01-06"



Which makes me think the solution for week-0s is to subtract 7:


as.Date("2014-00-1", "%Y-%W-%u") - 7
[1] "2013-12-30"



Upon reading the documentation for as.Date, this behavior may differ for you and me because of "locale-specific conversions". In any case, you can write your own function to handle your week-0s:


as.Date


myfun <- function(year, week)
if (week == 0)
as.Date(paste(year, "01", "1", sep="-"), "%Y-%W-%u") - 7
else
as.Date(paste(year, week, "1", sep="-"), "%Y-%W-%u")






You are correct that it appears to be a locale-specific issue. Thanks
– cdeterman
Aug 14 at 20:47






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

Creating a leaderboard in HTML/JS