Search code examples
pythonrcode-translation

Weekday alogorithm conversion from Python into R?


I've written the following function in Python. For any date it works out the correct Week Ending or Commencing date. I can't figure out how to write this in R. Anyone have any ideas?

def Week_dates(dt, day, we=False):
    """
    dt is a date
    day is string like 'sat' or 'mon'
    """
    day = day.lower()
    days = ['mon','tue','wed','thu','fri','sat','sun']

    if we:
        day_num = (days.index(day) + 1) % 7
    else:
        day_num = days.index(day)

    day_offset = (dt.weekday() + 7-day_num) % 7
    return dt - timedelta(days=day_offset) + timedelta(days=(6 * we))

Solution

  • Please see as below using lubridate package:

    Week_dates <- function(dt, day, we = FALSE) {
      require(lubridate)
      day <- tolower(day)
      days <- c("mon","tue","wed","thu","fri","sat","sun")
      if (we) {
        day_num <- (match(day, days) + 1) %% 7
      } else {
        day_num <- match(day, days) + 1
      }
      day_off_set <- (wday(dt) + 7 - day_num) %% 7
      dt - as.period(day_off_set, unit = "days") + as.period(6 * we, unit = "days")
    }
    
    Week_dates(ymd("2012/10/12"), "mon")
    # [1] "2012-10-08"