Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get week numbers from dates?

Looking for a function in R to convert dates into week numbers (of year) I went for week from package data.table. However, I observed some strange behaviour:

> week("2014-03-16") # Sun, expecting 11 [1] 11 > week("2014-03-17") # Mon, expecting 12 [1] 11 > week("2014-03-18") # Tue, expecting 12 [1] 12 

Why is the week number switching to 12 on tuesday, instead of monday? What am I missing? (Timezone should be irrelevant as there are just dates?!)

Other suggestions for (base) R functions are appreciated as well.

like image 520
Christian Borck Avatar asked Mar 16 '14 16:03

Christian Borck


People also ask

Can Excel calculate weeks between dates?

To find out how many weeks there are between two dates, you can use the DATEDIF function with "D" unit to return the difference in days, and then divide the result by 7. Where A2 is the start date and B2 is the end date of the period you are calculating.

How do you convert a date to a week number in a month?

=INT((DAY(B5)-1)/7)+1 Here, first using the DAY function we get the value of a day of the date in Cell B5. Then, we subtracted the value by 1 and divided it by 7 to get the day into the week number of the month.


2 Answers

Base package

Using the function strftime passing the argument %V to obtain the week of the year as decimal number (01–53) as defined in ISO 8601. (More details in the documentarion: ?strftime)

strftime(c("2014-03-16", "2014-03-17","2014-03-18", "2014-01-01"), format = "%V") 

Output:

[1] "11" "12" "12" "01" 
like image 158
mpalanco Avatar answered Sep 18 '22 08:09

mpalanco


if you try with lubridate:

library(lubridate) lubridate::week(ymd("2014-03-16", "2014-03-17","2014-03-18", '2014-01-01'))  [1] 11 11 12  1 

The pattern is the same. Try isoweek

lubridate::isoweek(ymd("2014-03-16", "2014-03-17","2014-03-18", '2014-01-01')) [1] 11 12 12  1 
like image 28
Paulo E. Cardoso Avatar answered Sep 20 '22 08:09

Paulo E. Cardoso