Search code examples
rlubridate

Find last week from date object


I have a date object formatted as YYYY-MM-DD on multiple years. I want to get yesterday, last week and last month from it. For yesterday, I can simply do Sys.Data()-1 and it gives me yesterday which I can compare with the data object.

However, I am struggling to find last week and last month. For last month, I can use lubridate package to get month(data)-1 the last month's number. Similarly, my criteria for a week is that it should be from Monday till Sunday. The week() method from lubridate gives me the number of week of the year. But since my data is on multiple years, they will repeat over each year.

Is there a way to get last month and last week's dates from today so i can compare them with my date object. Or is there another better way to find last month and last week from that data object?

For example, an ideal scenario would be following

        date       type
1 2021-04-09  yesterday
2 2021-04-01  last_week
3 2021-03-01 last_month

Solution

  • You can take help of lubridate functions.

    library(dplyr)
    library(lubridate)
    
    df %>%
      mutate(yesterday = date - 1, 
             last_week = floor_date(date, 'week') - 6, 
             last_month = floor_date(date, 'month') %m-% months(1))
    
    #        date  yesterday  last_week last_month
    #1 2021-04-10 2021-04-09 2021-03-29 2021-03-01
    #2 2019-02-03 2019-02-02 2019-01-28 2019-01-01
    #3 2020-05-06 2020-05-05 2020-04-27 2020-04-01
    

    data

    df <- data.frame(date = c(Sys.Date(), as.Date(c('2019-02-03', '2020-05-06'))))