convert year week string to date

给你一囗甜甜゛ 提交于 2019-12-11 05:28:37

问题


I have a column of strings in my data set formatted as year week (e.g. '201401' is equivalent to 7th April 2014, or the first fiscal week of the year)

I am trying to convert these to a proper date so I can manipulate them later, however I always receive the dame date for a given year, specifically the 14th of April.

e.g.

test_set <- c('201401', '201402', '201403')
as.Date(test_set, '%Y%U')

gives me:

[1] "2014-04-14" "2014-04-14" "2014-04-14"

回答1:


Try something like this:

> test_set <- c('201401', '201402', '201403')
> 
> extractDate <- function(dateString, fiscalStart = as.Date("2014-04-01")) {
+   week <- substr(dateString, 5, 6)
+   currentDate <- fiscalStart + 7 * as.numeric(week) - 1
+   currentDate
+ }
> 
> extractDate(test_set)
[1] "2014-04-07" "2014-04-14" "2014-04-21"

Basically, I'm extracting the weeks from the start of the year, converting it to days and then adding that number of days to the start of the fiscal year (less 1 day to make things line up).




回答2:


Not 100% sure what is your desired output but this may work

as.Date(paste0(substr(test_set, 1, 4), "-04-07")) +   
    (as.numeric(substr(test_set, 5, 6)) - 1) * 7

# [1] "2014-04-07" "2014-04-14" "2014-04-21"


来源:https://stackoverflow.com/questions/29631363/convert-year-week-string-to-date

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!