Obtaining last Friday's date
Asked Answered
R

5

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.

Replicate answered 10/3, 2015 at 18:42 Comment(0)
S
14

I think this should work:

library(lubridate)

Sys.Date() - wday(Sys.Date() + 1)
Strohben answered 10/3, 2015 at 18:47 Comment(0)
O
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.

Oscillogram answered 10/3, 2015 at 19:3 Comment(1)
I definitely was not expecting there to be a ready-made function for this. Cool.Enyedy
M
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   
Marissamarist answered 10/3, 2015 at 18:54 Comment(0)
L
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)
Ligule answered 10/3, 2015 at 18:48 Comment(2)
I expect the OP would like this to work for more than just Tuesdays.Cheetah
While that may be true, it wasn't specified. I've added a solution using base.Ligule
C
0
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"))
Comfit answered 27/9, 2023 at 15:17 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.