Mamba
Mamba

Reputation: 1203

How to change to Year Month Week format?

I have dates in year month day format that I want to convert to year month week format like so:

date            dateweek
2015-02-18   -> 2015-02-8
2015-02-19   -> 2015-02-8
2015-02-20   -> ....
2015-02-21   
2015-02-22   
2015-02-23   
2015-02-24      ...
2015-02-25   -> 2015-02-9
2015-02-26   -> 2015-02-9
2015-02-27   -> 2015-02-9

I tried

data$dateweek <- week(as.POSIXlt(data$date))

but that returns only weeks without the corresponding year and month.

I also tried:

data$dateweek <- as.POSIXct('2015-02-18')
data$dateweek <- format(data$dateweek, '%Y-%m-%U')
# data$dateweek <- format(as.POSIXct(data$date), '%Y-%m-%U')

but the corresponding columns look strange:

date         datetime
2015-01-01  2015-01-00
2015-01-02  2015-01-00  
2015-01-03  2015-01-00  
2015-01-04  2015-01-01  
2015-01-05  2015-01-01  
2015-01-06  2015-01-01  
2015-01-07  2015-01-01  
2015-01-08  2015-01-01  
2015-01-09  2015-01-01  
2015-01-10  2015-01-01  
2015-01-11  2015-01-02

Upvotes: 4

Views: 4210

Answers (1)

LyzandeR
LyzandeR

Reputation: 37879

You need to use the '%Y-%m-%V format to change it:

mydate <- as.POSIXct('2015-02-18')

> format(mydate, '%Y-%m-%V')
[1] "2015-02-08"

From the documentation strptime:

%V

Week of the year as decimal number (00–53) as defined in ISO 8601. If the week (starting on Monday) containing 1 January has four or more days in the new year, then it is considered week 1. Otherwise, it is the last week of the previous year, and the next week is week 1. (Accepted but ignored on input.)

and there is also (The US convention) :

%U

Week of the year as decimal number (00–53) using Sunday as the first day 1 of the week (and typically with the first Sunday of the year as day 1 of week 1). The US convention.

It really depends on which one you want to use for your case.

mydate <- as.POSIXct('2015-02-18')

> format(mydate, '%Y-%m-%U')
[1] "2015-02-07"

In your case you should do:

data$dateweek <- format(as.POSIXct(data$date), '%Y-%m-%U')

Upvotes: 8

Related Questions