R: getting last friday

I can get the date today:

Sys.Date( ) 

But how do I get on last Friday? I tried:

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

But it gives an error.

thanks for the help

+5
source share
4 answers

I think this should work:

 library(lubridate) Sys.Date() - wday(Sys.Date() + 1) 
+9
source

Try the following:

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

where lastfri matches the function of the nextfri single line in this zoo vignette, zoo quickref vignette , except that ceiling is replaced with floor . Note that lastfri vectorized, that is, it can take a vector of input dates and output a vector of output dates. For instance,

 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 continue to receive March 6th until the day reaches next Friday, at this moment last Friday is March 13th.

In addition: next Friday - Friday the 13th.

+10
source

Here is a function that finds the latest 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: ie

 Sun Mon Tues Wed Thurs Fri Sat 
+5
source

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) 
+1
source

Source: https://habr.com/ru/post/1215083/


All Articles