It seems the Internet has not answered this question for R yet:
If I have a date. Say the 20th of march: as.Date(\"2015-03-20\") how do I get, in R, the previous Sun
One way:
d<-as.Date("2015-03-20")
d-as.POSIXlt(d)$wday
## [1] "2015-03-15"
There;s also the more hackish way, using the fact that dates are represented as integers with day zero being a Thursday (Jan 1 1970):
d-((as.numeric(d)+4)%% 7)
## [1] "2015-03-15"
cut(date_var, breaks='week', start.on.monday = F)
This works for me. It is available in base r and is bound to be faster. breaks can be used to find start of day, week, month, quarter, year.
Read ?cut & ?cut.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
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"
Reading through the lubridate documentation, I found an 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: (for monday)
day(date)<-day(date)+1
and substract 7 days if it is greater than the original date.