首页 > 解决方案 > 将 year.week 转换为 date

问题描述

我有 YYYY.week 格式的时间:

x <- c("2016.49", "2016.50", "2016.51", "2016.52", "2017.01", "2017.02", "2017.03", "2017.04", "2017.05")

有没有办法像这样创建将其转换为日期变量(日期不正确,但这是所需的格式):

as.Date(x[1])
"2017-02-01"

标签: rdatelubridate

解决方案


一种lubridate选择可能是:

ymd(paste0(substr(x, 1, 4), "-01", "-01"))+weeks(as.numeric(substr(x, nchar(x)-1, nchar(x)))-1)

 [1] "2016-12-02" "2016-12-09" "2016-12-16" "2016-12-23" "2017-01-01"

样本数据:

x <- c("2016.49", "2016.50", "2016.51", "2016.52", "2017.01")

推荐阅读