Search code examples
rdatextszooquantmod

Change weekend to weekday


I have a dataframe. Some dates fall on the weekend. However I would like to change all weekend dates to the past Friday.

 as.Date(aapl_earnings$Date, "%Y/%m/%d")
 [1] "2018-04-30" "2018-01-31" "2017-11-01" "2017-07-31" "2017-05-01" "2017-01-30" "2016-10-24"
 [8] "2016-07-25" "2016-04-25" "2016-01-25" "2015-10-26" "2015-07-20" "2015-04-26" "2015-01-26"
[15] "2014-10-19" "2014-07-21" "2014-04-22" "2014-01-26" "2013-10-27"

Solution

  • We can use a nested ifelse here and check the day of the week using weekdays and adjust the date accordingly.

    dates <- weekdays(as.Date(x))
    
    as.Date(ifelse(dates == "Saturday", x - 1, 
            ifelse(dates == "Sunday", x - 2, x)), origin = "1970-01-01")
    
    #[1]"2018-04-30" "2018-01-31" "2017-11-01" "2017-07-31" "2017-05-01" "2017-01-30"
    #[7]"2016-10-24" "2016-07-25" "2016-04-25" "2016-01-25" "2015-10-26" "2015-07-20"
    #[13]"2015-04-24" "2015-01-26" "2014-10-17" "2014-07-21" "2014-04-22" "2014-01-24"
    #[19]"2013-10-25"
    

    Or we can also use case_when from dplyr which is more verbose.

    library(dplyr)
    aapl_earnings <- data.frame(Date = as.Date(x))
    
    aapl_earnings %>%
         mutate(date = weekdays(Date), 
                new_date = case_when(date == "Saturday" ~ Date - 1, 
                                     date == "Sunday" ~ Date - 2, 
                                     TRUE ~ Date)) %>%
         select(-date)
    
    #         Date   new_date
    #1  2018-04-30 2018-04-30
    #2  2018-01-31 2018-01-31
    #3  2017-11-01 2017-11-01
    #4  2017-07-31 2017-07-31
    #5  2017-05-01 2017-05-01
    #6  2017-01-30 2017-01-30
    #7  2016-10-24 2016-10-24
    #8  2016-07-25 2016-07-25
    #9  2016-04-25 2016-04-25
    #10 2016-01-25 2016-01-25
    #11 2015-10-26 2015-10-26
    #12 2015-07-20 2015-07-20
    #13 2015-04-26 2015-04-24
    #14 2015-01-26 2015-01-26
    #15 2014-10-19 2014-10-17
    #16 2014-07-21 2014-07-21
    #17 2014-04-22 2014-04-22
    #18 2014-01-26 2014-01-24
    #19 2013-10-27 2013-10-25
    

    data

    x <- c("2018-04-30","2018-01-31","2017-11-01","2017-07-31","2017-05-01",
        "2017-01-30","2016-10-24","2016-07-25","2016-04-25","2016-01-25","2015-10-26",
        "2015-07-20","2015-04-26","2015-01-26" ,"2014-10-19","2014-07-21","2014-04-22",
        "2014-01-26", "2013-10-27")