rlubridate

How to find next particular day?


I need to find all 'next friday' corresponding to a set of dates.

For instance 2015-08-03 (Monday 3rd, August, 2015) as an input should return 2015-08-07 (Friday 7th, August, 2015) as an output.

I could not find a way to manage this need while reading lubridate's vignette, how would you proceed?

library(lubridate) 
date <- "2015-08-03"
date <- wmd(date)
wday(date, label = TRUE)

Solution

  • Try this function:

    nextweekday <- function(date, wday) {
      date <- as.Date(date)
      diff <- wday - wday(date)
      if( diff < 0 )
        diff <- diff + 7
      return(date + diff)
    }
    

    You insert your date and the desired wday (Sunday = 1, Monday = 2, ...) and get the result you wanted.