How to Find Previous Sunday in R

It seems that the Internet has not yet answered this question for R:

If I have a date. Say March 20th: as.Date ("2015-03-20") how can I get to R, the previous Sunday? that is, in the above example, as .Date ("2015-03-15").

+12
source share
4 answers

Here is one approach:

d <- as.Date("2015-03-18") prev.days <- seq(d-6,d,by='day') prev.days[weekdays(prev.days)=='Sunday'] # [1] "2015-03-15" 
+8
source

After reading the lubridate documentation, I found the answer.

 library(lubridate) date <- as.Date("2015-03-20") previous_sunday <- floor_date(date, "week") 

To get the previous Monday, tues, etc., just add the required number of days: (Monday)

 day(date)<-day(date)+1 

and subtract 7 days if it is more than the original date.

+17
source

One of the methods:

 d<-as.Date("2015-03-20") d-as.POSIXlt(d)$wday ## [1] "2015-03-15" 

There's also a more hacky way, using the fact that dates are represented as integers with day zero being Thursday (January 1, 1970):

 d-((as.numeric(d)+4)%% 7) ## [1] "2015-03-15" 
+4
source
 cut(date_var, breaks='week', start.on.monday = F) 

This works for me. It is available in the r database and should be faster. Breaks can be used to search for the beginning of the day, week, month, quarter, year.

To read? Cut and? Cut. the date

 Sys.Date() 

[1] "2017-12-23"

 cut(Sys.Date(), breaks = 'week', start.on.monday = F) 

[1] 2017-12-17 Levels: 2017-12-17

 cut(Sys.Date(), breaks = 'month') 

[1] 2017-12-01 levels: 2017-12-01

 cut(Sys.Date(), breaks = 'quarter') 

[1] 2017-10-01 levels: 2017-10-01

 cut(Sys.Date(), breaks = 'year') 

[1] 2017-01-01 Levels: 2017-01-01

+4
source

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


All Articles