-1

The title says it all, but in case I wasn't clear enough I'll give a scenario:

Let's say I run my program next week. I would like my variable to return the date in the form of yyyy-mm-dd for the Friday of that week. Whether I run it on Monday or Wednesday or whenever, my variable is the date of the Friday of that week.

JackW24
  • 135
  • 9

1 Answers1

3

A date will give you its 'weekday'. If you convert to POSIXlt you get it via the wday field. As Friday has a value of 5, you just add the difference to 5 to the date.

Function:

getFriday <- function(d) d + (5 - as.POSIXlt(d)$wday)

Examples for this week's Monday and Wednesday:

> getFriday(as.Date("2021-07-25")) 
[1] "2021-07-30" 
> getFriday(as.Date("2021-07-27")) 
[1] "2021-07-30" 
> 

You can easily control for inputs that a Sat or Sun, and error out, or adjust accordingly. But the key is that this is computable as a difference from your input date to its desired next Friday. (And of course you should check that the input is a date, or convertible to a date, and error out if not ...)

Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725