Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtaining last Friday's date

Tags:

date

r

weekday

xts

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.

like image 465
adam.888 Avatar asked Mar 10 '15 18:03

adam.888


4 Answers

I think this should work:

library(lubridate)

Sys.Date() - wday(Sys.Date() + 1)
like image 157
JasonAizkalns Avatar answered Sep 29 '22 15:09

JasonAizkalns


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.

like image 23
G. Grothendieck Avatar answered Sep 29 '22 17:09

G. Grothendieck


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   
like image 25
jalapic Avatar answered Sep 29 '22 16:09

jalapic


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)
like image 45
Andrew Taylor Avatar answered Sep 29 '22 16:09

Andrew Taylor