Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identify dates in the same week

Tags:

r

Given a vector of dates (could span multiple years):

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

I'd like to generate an identifier that groups dates into weeks. So assuming a calendar that starts on Sunday:

  • the 26th to the 29th would produce the same identifier
  • the 30th through the 5th have the same id
  • the 6th through the 9th have the same id

Here's a flawed attempt:

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

It sees the 31th and the 1st as different weeks (no surprise). I'm looking for something similar to strftime that will generate an identifier (character, numeric, whatever) that I can use to group the dates by week.

I'm sure there's some clever function out there already.

like image 361
SFun28 Avatar asked Dec 12 '12 17:12

SFun28


2 Answers

This will assign a unique integer to groups of dates that fall within a given 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
like image 163
Josh O'Brien Avatar answered Oct 12 '22 06:10

Josh O'Brien


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
like image 41
agstudy Avatar answered Oct 12 '22 06:10

agstudy