wentworth
wentworth

Reputation: 43

R as.Date() convert year and week number to date

I'm running into trouble converting a year + month string containing week number 53 using the as.Date() function in R.

The code works for the top example for week number 52 but returns NA for the bottom example for week number 53.

a <- "2017521"
as.Date(a, '%Y%W%u')
"2017-12-25"

b <- "2017531"
as.Date(b, '%Y%W%u')
NA

Upvotes: 1

Views: 3031

Answers (1)

jasbner
jasbner

Reputation: 2283

You're getting NA for b <- "2017531" because you're trying to reference a date that did not exist.

This has to do with the way you formatted your date, and the way the calendar is initiated.

%W refers to the numerical week 00-53

%u refers to the day of the week 1-7 Monday is 1

b <- "2017531"
as.Date(b, '%Y%W%u')
# [1] NA

Week 53 day 1 would refer to Monday of the 53rd week. But the only day of the week that occurred on the 53rd week of 2017 was Sunday.

c <- "2017537"
as.Date(a, '%Y%W%u')
# [1] "2017-12-31"

You can further confirm this by checking the date Saturday of week 52:

d <- "2017526"
as.Date(a, '%Y%W%u')
# [1] "2017-12-30"

Upvotes: 2

Related Questions