Home > Software design >  If today's date is Saturday, Sunday, or Monday then set today's date to last Friday, else
If today's date is Saturday, Sunday, or Monday then set today's date to last Friday, else

Time:10-05

With only the System Libraries (preferably), how do I set today's date to last Friday if today falls on Saturday, Sunday, or Monday, else set to today's date?

todaysDate <- Sys.Date()

if(weekdays(todaysDate) == "Saturday" || weekdays(todaysDate) == "Sunday" 
   || weekdays(todaysDate) == "Monday") {
  todaysDate == ???} else {
    todaysDate <- Sys.Date()
  }

Thanks in advance.


Systems used:

  • R version: 4.1.1 (2021-08-10)
  • RStudio version: 1.4.1717
  • OS: macOS Catalina version 10.15.7 and macOS Big Sur version 11.6

CodePudding user response:

You could use the logic:

todaysDate <- Sys.Date()
today <- weekdays(todaysDate)

if(today == "Saturday")
  todaysDate <- todaysDate - 1
else if (today == "Sunday") 
   todaysDate <- todaysDate - 2
else if (today == "Monday") 
   todaysDate <- todaysDate - 3

CodePudding user response:

We may do this with match on sequence of dates before the 'todaysDate' that matches the 'Friday'

if(weekdays(todaysDate) %in% c("Saturday", "Sunday", "Monday")) {
      s1 <- todaysDate - (1:8)
      todaysDate <- s1[match('Friday', weekdays(s1))]
    }

CodePudding user response:

An other solution might be a recursive function:

dayFun <- function(x) {
  if (weekdays(x) %in% c("Sunday", "Saterday", "Monday")) {
    return(dayFun(x-1))
  } else {
    return(x)
  }
}
dayFun(Sys.Date())

note that the result of weekdays depends on the language setting of the machine so if that is a concern some more thoughts are needed

  •  Tags:  
  • r
  • Related