Search code examples
rtidyverselubridate

Is there an R function to add weekending Sunday by a given date


I would like to mutate a week-ending Sunday to a dataset in R. For example enter image description here

This is what I have so far:

x <- seq(Sys.Date(), by = "1 day", length.out = 21)
data.frame(
  x = x,
  weekday = weekdays(x),
  next_friday = ceiling_date(x, "week") + 
    ifelse(weekdays(x) %in% c("Saturday", "Sunday"), -7,0)
)

Solution

  • Perhaps simpler:

    x + (7-as.integer(format(x, "%u")))
    #  [1] "2021-04-11" "2021-04-18" "2021-04-18" "2021-04-18" "2021-04-18" "2021-04-18" "2021-04-18"
    #  [8] "2021-04-18" "2021-04-25" "2021-04-25" "2021-04-25" "2021-04-25" "2021-04-25" "2021-04-25"
    # [15] "2021-04-25" "2021-05-02" "2021-05-02" "2021-05-02" "2021-05-02" "2021-05-02" "2021-05-02"
    

    Bigger:

    dat <- data.frame(
      x = x,
      weekday = weekdays(x),
      next_sunday_date = x + (7-as.integer(format(x, "%u")))
    )
    transform(dat, next_sunday_weekday = weekdays(next_sunday_date))
    #             x   weekday next_sunday_date next_sunday_weekday
    # 1  2021-04-11    Sunday       2021-04-11              Sunday
    # 2  2021-04-12    Monday       2021-04-18              Sunday
    # 3  2021-04-13   Tuesday       2021-04-18              Sunday
    # 4  2021-04-14 Wednesday       2021-04-18              Sunday
    # 5  2021-04-15  Thursday       2021-04-18              Sunday
    # 6  2021-04-16    Friday       2021-04-18              Sunday
    # 7  2021-04-17  Saturday       2021-04-18              Sunday
    # 8  2021-04-18    Sunday       2021-04-18              Sunday
    # 9  2021-04-19    Monday       2021-04-25              Sunday
    # 10 2021-04-20   Tuesday       2021-04-25              Sunday
    # 11 2021-04-21 Wednesday       2021-04-25              Sunday
    # 12 2021-04-22  Thursday       2021-04-25              Sunday
    # 13 2021-04-23    Friday       2021-04-25              Sunday
    # 14 2021-04-24  Saturday       2021-04-25              Sunday
    # 15 2021-04-25    Sunday       2021-04-25              Sunday
    # 16 2021-04-26    Monday       2021-05-02              Sunday
    # 17 2021-04-27   Tuesday       2021-05-02              Sunday
    # 18 2021-04-28 Wednesday       2021-05-02              Sunday
    # 19 2021-04-29  Thursday       2021-05-02              Sunday
    # 20 2021-04-30    Friday       2021-05-02              Sunday
    # 21 2021-05-01  Saturday       2021-05-02              Sunday