首页 > 解决方案 > R:如何从年周中提取完整日期?

问题描述

我有以下格式的日期(年和周数):

year_week
201804
201938
201745
201402
201510

我需要以这种格式获取完整日期:2018-02-26 (%Y-%m-%d). 为此,我使用下一个代码:

dt[, full_date := format(ISOweek2date(sub("(\\d{4})(\\d{2})", "\\1-W\\2-1", year_week)),"%Y-%m-%d")]

但是,我有以下错误:

"Error: all(is.na(weekdate) | stringr::str_detect(weekdate, kPattern)) is not TRUE"

如何以另一种方式获得完整日期?为什么我有这个错误?

非常感谢您的帮助!

PS 星期日或星期一可以用作一周的第一天。

标签: rregexdatelubridatestringr

解决方案


您可以将工作日添加到日期并使用

as.Date(paste0(df$year_week, 1),"%Y%U%u")
#[1] "2018-01-29" "2019-09-23" "2017-11-06" "2014-01-13" "2015-03-09"

数据

df <- structure(list(year_week = c(201804L, 201938L, 201745L, 201402L, 
201510L)), class = "data.frame", row.names = c(NA, -5L))

推荐阅读