Convert week number to date

后端 未结 4 604
离开以前
离开以前 2020-11-28 11:30

I have a data frame in R with the week of the year that I would like to convert to a date. I know I have to pick a year and a day of the week so I am fixing those values at

4条回答
  •  渐次进展
    2020-11-28 12:00

    An alternative solution is to use date arithmetic from the lubridate package:

    lubridate::ymd( "2014-01-01" ) + lubridate::weeks( df$Week - 1 )
    

    The -1 is necessary because 2014-01-01 is already week 1. In other words, we want:

    • df$Week == 1 to map to 2014-01-01 (which is ymd("2014-01-01") + weeks(1-1))
    • df$Week == 2 to map to 2014-01-08 (which is ymd("2014-01-01") + weeks(2-1))
    • and so on.

提交回复
热议问题