从 Python 到 R 的工作日算法转换?

Weekday alogorithm conversion from Python into R?

我在Python中编写了以下函数。对于任何日期,它都会计算出正确的周结束或开始日期。我不知道如何用 R 写这个。有人有什么想法吗?

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))

请使用lubridate包查看如下:

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"