简体   繁体   中英

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

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM