Determine dates in the same week

For a date vector (may span several years):

exampleDates = as.Date( 1 : 15, origin = as.Date( "2012-12-25" ) )

I would like to generate an identifier that groups dates into weeks. So, provided that the calendar starts on Sunday:

  • from the 26th to the 29th the same identifier will be issued
  • 30th to 5th have the same identifier
  • from 6th to 9th have the same identifier

Here is an incorrect attempt:

strftime( exampleDates , format = "%Y%W" )

He sees 31st and 1st places as different weeks (not surprisingly). I'm looking for something similar to strftime that will generate an identifier (character, numeric, any) that I can use to group dates by week.

I am sure that there is some kind of smart function.

+8
r
source share
2 answers

This assigns a unique integer to the date groups that are relevant for this week:

 origin <- as.Date("2012-12-9") ## A Sunday weekID <- as.numeric(exampleDates - origin) %/% 7 data.frame(date = exampleDates, weekday = weekdays(exampleDates), week = weekID) # date weekday week # 1 2012-12-26 Wednesday 2 # 2 2012-12-27 Thursday 2 # 3 2012-12-28 Friday 2 # 4 2012-12-29 Saturday 2 # 5 2012-12-30 Sunday 3 # 6 2012-12-31 Monday 3 # 7 2013-01-01 Tuesday 3 # 8 2013-01-02 Wednesday 3 # 9 2013-01-03 Thursday 3 # 10 2013-01-04 Friday 3 # 11 2013-01-05 Saturday 3 # 12 2013-01-06 Sunday 4 # 13 2013-01-07 Monday 4 # 14 2013-01-08 Tuesday 4 # 15 2013-01-09 Wednesday 4 
+10
source share

using difftime,

 floor(difftime( exampleDates,as.Date( "2012-12-16" ), units = "week")) time differences in weeks [1] 1 2 2 2 2 2 2 2 3 3 3 3 3 3 3 
+4
source share

All Articles