Convert week number to date

后端 未结 4 603
离开以前
离开以前 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 11:45
    It will be like using 2nd year = (week-52), 3rd year  = (week -104)...so on
    
    for(i in 1:456548)
    {
      if (train[i,2] > 0 & train[i,2] <53)
      {
        train["weekdate"] <- as.Date(paste(2016, train$week, 1, sep="-"), "%Y-%U-%u")
      }
      if (train[i,2] > 52 & train[i,2] <105)
      {
        train["weekdate"] <- as.Date(paste(2017, (train$week-52), 1, sep="-"), "%Y-%U-%u")
      }
      if (train[i,2] > 104 & train[i,2] <150)
      {
        train["weekdate"] <- as.Date(paste(2018, (train$week-104), 1, sep="-"), "%Y-%U-%u")
      }
    
    }
    
    0 讨论(0)
  • 2020-11-28 11:54

    Another option with lubridate

    lubridate::parse_date_time(paste(2014, df$Week, 'Mon', sep="/"),'Y/W/a')
    
    0 讨论(0)
  • 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.
    0 讨论(0)
  • 2020-11-28 12:05

    as.Date is calling the 1 to 9 as NA as it is expects two digits for the week number and can't properly parse it.

    To fix it, add in some - to split things up:

    as.Date(paste(2014, df$Week, 1, sep="-"), "%Y-%U-%u")
    
    0 讨论(0)
提交回复
热议问题