简体   繁体   中英

convert year week string to date

I have a column of strings in my data set formatted as year week (eg '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.

eg

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

gives me:

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

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).

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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