简体   繁体   English

将周数转换为日期

[英]Convert week number to date

I have a data frame in R with the week of the year that I would like to convert to a date.我在 R 中有一个数据框,我想将其转换为日期。 I know I have to pick a year and a day of the week so I am fixing those values at 2014 and 1. Converting this to a date seems simple:我知道我必须选择一周中的一年和一天,所以我将这些值固定为 2014 和 1。将其转换为日期似乎很简单:

as.Date(paste(2014,df$Week,1,sep=""),"%Y%U%u")

But this code only works if week is greater than 9. Week 1 - 9 returns NA.但此代码仅在周大于 9 时有效。第 1 - 9 周返回 NA。 If I change the week to 01,02,03... it still returns NA.如果我将周更改为 01,02,03...它仍然返回 NA。

Anyone see what I am missing?有人看到我缺少什么吗?

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. as.Date将 1 到 9 称为 NA,因为它期望周数为两位数,并且无法正确解析它。

To fix it, add in some - to split things up:要修复它,请添加一些 - 将事情分开:

as.Date(paste(2014, df$Week, 1, sep="-"), "%Y-%U-%u")

An alternative solution is to use date arithmetic from the lubridate package:另一种解决方案是使用lubridate包中的日期算法:

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: -1是必需的,因为2014-01-01已经是第 1 周。换句话说,我们想要:

  • df$Week == 1 to map to 2014-01-01 (which is ymd("2014-01-01") + weeks(1-1) ) df$Week == 1映射到2014-01-01 (即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) ) df$Week == 2映射到2014-01-08 (即ymd("2014-01-01") + weeks(2-1)
  • and so on.等等。

Another alternative is to make sure that week numbers have two digits, which can be done using stringr::str_pad() , which will add a pad="0" to make sure there are width=2 digits:另一种选择是确保周数有两位数,这可以使用stringr::str_pad()来完成,这将添加一个pad="0"以确保有width=2位数字:

year <- 2015
week <- 1
as.Date(paste(year, week, "1", sep=""), "%Y%U%u")
#> [1] NA
as.Date(paste(year, stringr::str_pad(week,width=2, pad="0"), "1", sep=""), "%Y%U%u")
#> [1] "2015-01-05"
as.Date(paste(year, week, "1", sep="-"), "%Y-%U-%u")
#> [1] "2015-01-05"

Created on 2021-04-19 by the reprex package (v1.0.0)reprex 包(v1.0.0) 于 2021 年 4 月 19 日创建

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")
  }

}

Another option with lubridate lubridate另一种选择

lubridate::parse_date_time(paste(2014, df$Week, 1, sep="/"),'Y/W/w')

W - week number, w - weekday number, 0-6 (Sun-Sat) W - 周数, w - 工作日数,0-6(周日至周六)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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