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:
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With