Minnow Minnow - 1 month ago 8
R Question

How to convert datetime to first Sunday of the week in R

Goal: Convert a date object to a date that is the Sunday of the week; they should still function as a date object

For example, today would convert to

2016-10-16
, tomorrow would convert to the same.

Sample data:

library(lubridate)
dt <- Sys.Date()-days(1:20)

"2016-10-17" "2016-10-16" "2016-10-15" "2016-10-14" "2016-10-13" "2016-10-12" "2016-10-11"
"2016-10-10" "2016-10-09" "2016-10-08" "2016-10-07" "2016-10-06" "2016-10-05"
"2016-10-04" "2016-10-03" "2016-10-02"


Expected output:

"2016-10-16" "2016-10-16" "2016-10-09" "2016-10-09" "2016-10-09" "2016-10-09" "2016-10-09"
"2016-10-09" "2016-10-09" "2016-10-02" "2016-10-02" "2016-10-02" "2016-10-02"
"2016-10-02" "2016-10-02" "2016-10-02"


I've tried playing with
lubridate
,
zoo
and
xts
packages and
strptime
, but nothing quite serves the need. The function
yearweek
in MySQL does just what I want (note: package
sqldf
doesn't have that function).

This seems like something that would already have an answer, but had no luck with the search; C++, javascript, and Ruby, but nothing in R.

Answer

Here is another solution from start to finish -- no need for lubridate at any step along the way:

R> dt <- Sys.Date() - 1:20
R> newdt <- dt - as.POSIXlt(dt)$wday
R> data.frame(dt, newdt)
           dt      newdt
1  2016-10-16 2016-10-16
2  2016-10-15 2016-10-09
3  2016-10-14 2016-10-09
4  2016-10-13 2016-10-09
5  2016-10-12 2016-10-09
6  2016-10-11 2016-10-09
7  2016-10-10 2016-10-09
8  2016-10-09 2016-10-09
9  2016-10-08 2016-10-02
10 2016-10-07 2016-10-02
11 2016-10-06 2016-10-02
12 2016-10-05 2016-10-02
13 2016-10-04 2016-10-02
14 2016-10-03 2016-10-02
15 2016-10-02 2016-10-02
16 2016-10-01 2016-09-25
17 2016-09-30 2016-09-25
18 2016-09-29 2016-09-25
19 2016-09-28 2016-09-25
20 2016-09-27 2016-09-25
R>