Search code examples
rdatedayofweek

How to Get the Same Weekday Last Year Given any Given Year?


I would like to get the same day last year given any year. How can I best do this in R. For example, given Sunday 2010/01/03, I would like to obtain the Sunday of the same week the year before.

# "Sunday"
weekdays(as.Date("2010/01/03", format="%Y/%m/%d"))

# "Saturday"
weekdays(as.Date("2009/01/03", format="%Y/%m/%d"))

Solution

  • To find the same weekday one year ago, simply subtract 52 weeks or 364 days from the given date:

    d <- as.Date("2010-01-03")
    weekdays(d)
    #[1] "Sunday"
    d - 52L * 7L
    #[1] "2009-01-04"
    weekdays(d - 52L * 7L)
    #[1] "Sunday"
    

    Please note that the calendar year has 365 days (or 366 days in a leap year) which is one or two days more than 52 weeks. So, the calendar date of the same weekday one year ago moves on by one or two days. (Or, it explains why New Year's Eve is always on a different weekday.)