Search code examples
rdatecut

Define which weekdays the cut function starts at?


I would like Cut() to follow the dateRange object that I defined below which starts on Sunday. It appears that the cut function starts on Saturday but I need it to start on Sunday

startDate = "2011-07-03"; endDate = "2011-8-07" ## starts on Sunday and ends on Sunday
dateRange <- seq(as.Date(startDate), to = as.Date(endDate), by = "day") ## This step is okay
dateRange
cut(dateRange, "weeks", ordered_result = TRUE) ## This I think where the problem is, it starts on the previous Saturday

Please let me know how I can have the output of the cut() provides the same number of bins as the test object DateRange.

Here is how I use the cut() function

dataSet <- runif(length(dateRange))
weeklyList <- split(dataSet, cut(dateRange, "weeks", ordered_result = TRUE)) ## This is how I use the cut() to bin my data.

Your technical expertise is greatly appreciated.


Solution

  • As Frank says, the cut function is beginning on Monday, not Saturday. You can change this by using the start.on.monday option to cut.

    > weeklyList <- split(dataSet, cut(dateRange, "weeks", ordered_result = TRUE, start.on.monday = FALSE))
    > weeklyList
    $`2011-07-03`
    [1] 0.8208915 0.3073812 0.7427008 0.6856026 0.7733733 0.6258881 0.5222145
    
    $`2011-07-10`
    [1] 0.10739317 0.43350298 0.17186167 0.90407228 0.95883564 0.60972446 0.08929786
    
    $`2011-07-17`
    [1] 0.61130816 0.06738358 0.71603027 0.51067438 0.32632549 0.52515075 0.92037779
    
    $`2011-07-24`
    [1] 0.1391482 0.4253714 0.2754398 0.5745825 0.8776789 0.2088506 0.9773318
    
    $`2011-07-31`
    [1] 0.58218481 0.05610510 0.05400599 0.75924478 0.98367785 0.42556051 0.77251544
    
    $`2011-08-07`
    [1] 0.5907571