Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find Previous Sunday in R

Tags:

date

r

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 Sunday? i.e., in the above example, as.Date("2015-03-15").

like image 894
patapouf_ai Avatar asked Mar 20 '15 16:03

patapouf_ai


Video Answer


2 Answers

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.

like image 152
patapouf_ai Avatar answered Sep 20 '22 15:09

patapouf_ai


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"
like image 25
Marat Talipov Avatar answered Sep 18 '22 15:09

Marat Talipov