9

I can get today's date:

Sys.Date( )

But how do I get last Friday's date?

I tried:

library(xts)

date1 <- Sys.Date( ) 
to.weekly(date1 )

But this gives an error.

zx8754
  • 52,746
  • 12
  • 114
  • 209
adam.888
  • 7,686
  • 17
  • 70
  • 105

4 Answers4

14

I think this should work:

library(lubridate)

Sys.Date() - wday(Sys.Date() + 1)
JasonAizkalns
  • 20,243
  • 8
  • 57
  • 116
11

Try this:

library(zoo)
lastfri(Sys.Date())

where lastfri is the same as the one line function nextfri in the this zoo vignette, zoo quickref vignette, except that ceiling is replaced with floor. Note that lastfri is vectorized, i.e. it can take a vector of input dates and produces a vector of output dates. For example,

library(zoo)
Sys.Date()
## 2015-03-10
lastfri(Sys.Date() + 0:6)
## [1] "2015-03-06" "2015-03-06" "2015-03-06" "2015-03-13" "2015-03-13"
## [6] "2015-03-13" "2015-03-13"

Thus last Friday was March 6th and we keep getting March 6th until the day advances to to next Friday at which point the last Friday is March 13th.

Aside: Next Friday is Friday the 13th.

G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
6

Here is a function that finds the last date for any day of the week:

getlastdate <- function(day) {
library(lubridate)
dates <- seq((Sys.Date()-7), (Sys.Date()-1), by="days")
dates[wday(dates, label=T)==day]
}

getlastdate("Mon")  

# "2015-03-09"

Enter the day of the week in abbreviated format: i.e.

Sun   Mon Tues  Wed   Thurs Fri   Sat   
jalapic
  • 13,792
  • 8
  • 57
  • 87
1

Last Friday was 4 days ago, thus:

Sys.Date()-4

> Sys.Date()-4
[1] "2015-03-06"

OR for any day of the week, using base:

Sys.Date()-(as.POSIXlt(Sys.Date())$wday+2)
Andrew Taylor
  • 3,438
  • 1
  • 26
  • 47