rdatedplyrlubridatebizdays

R how to get sixth workday of the month


I have a vector of business dates:

require(bizdays)
cal <- create.calendar(name='MyCalendar', weekdays=c('sunday', 'saturday'))
startdate = as.Date(Sys.Date()) %m-% years(5) # today minus 5yrs
enddate = as.Date(Sys.Date())
dates = bizseq(startdate,enddate, cal)

Now I want to extract every 6th workday of very month from the dates vector, any ideas how to do this?

Thanks,

Jelle


Solution

  • You're really just looking to get every 6th value of the vector by group of month and year. We can use base ave() with lubridate to get what you want:

    library(bizdays)
    library(lubridate)
    
    m_days <- ave(1:length(dates), month(dates), year(dates), FUN = seq_along)
    result <- dates[m_days %% 6 == 0]
    head(result)
    #> [1] "2015-08-28" "2015-09-08" "2015-09-16" "2015-09-24" "2015-10-08"
    #> [6] "2015-10-16"