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.
I think this should work:
library(lubridate)
Sys.Date() - wday(Sys.Date() + 1)
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.
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With