Lubridate week() to find consecutive week number for multi-year periods

To get the interval from a particular date to another date, you can just subtract...

If tda is your vector of dates, then

tda - min(tda)

will be the difference in seconds between them.

To get the units out in weeks:

(tda - min(tda))/eweeks(1)

To do it from a particular date:

tda - ymd(19960101)

This gives the number of days from 1996 to each value.

From there, you can divide by days per week, or seconds per week.

(tda - ymd(19960101))/eweeks(1)

To get only the integer part, and starting from January 2012:

trunc((tda - ymd(20111225))/eweeks(1))

Test data:

tda = ymd(c(20120101, 20120106, 20130101, 20130108))

Output:

 1  1 53 54

Since eweeks() is now deprecated, I thought I'd add to @beroe's answer.

If tda is your date vector, you can get the week numbers with:

weeknos <- (interval(min(tda), tda) %/% weeks(1)) + 1

where %/% causes integer division. ( 5 / 3 = 1.667; 5 %/% 3 = 1)


You can do something like this :

week(dat) +53*(year(dat)-min(year(dat)))

Tags:

R

Lubridate