adam.888
adam.888

Reputation: 7846

Obtaining last Friday's date

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.

Upvotes: 9

Views: 5538

Answers (5)

LMc
LMc

Reputation: 18732

library(clock)

dt <- as_naive_time(Sys.Date())
as.Date(time_point_shift(dt, weekday(6), which = "previous")) # sunday = 1

# OR use clock_weekdays

friday <- weekday(clock_weekdays$friday)
as.Date(time_point_shift(dt, friday, which = "previous"))

Wrapping this in a small function would look like (run on Wednesday, Dec 18, 2024 for reference):

prev_day <- function(day = "friday") {
  dt <- as_naive_time(Sys.Date())
  as.Date(time_point_shift(dt, weekday(clock_weekdays[[day]]), which = "previous"))
}
prev_day()
[1] "2024-12-13"

prev_day("monday")
[1] "2024-12-16"

Upvotes: 0

G. Grothendieck
G. Grothendieck

Reputation: 270195

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.

Upvotes: 11

Andrew Taylor
Andrew Taylor

Reputation: 3488

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)

Upvotes: 1

jalapic
jalapic

Reputation: 14212

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   

Upvotes: 6

JasonAizkalns
JasonAizkalns

Reputation: 20483

I think this should work:

library(lubridate)

Sys.Date() - wday(Sys.Date() + 1)

Upvotes: 14

Related Questions