如何将日期时间转换为R中一周的第一个星期日

Min*_*now 0 datetime r data-conversion

目标:将日期对象转换为星期日的日期; 它们仍然应该作为日期对象

例如,今天将转换为2016-10-16,明天将转换为相同.

样本数据:

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"
Run Code Online (Sandbox Code Playgroud)

预期产量:

"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"
Run Code Online (Sandbox Code Playgroud)

我试着玩lubridate,zooxts包和strptime,但没有相当的供应需求.yearweek MySQL中的函数正是我想要的(注意:包sqldf没有那个功能).

这似乎已经有了答案,但搜索没有运气; C++,javascript和Ruby,但R中没有任何内容.

Jos*_*ien 5

这里不需要润滑剂.您可以改为执行以下操作.

## `%w` returns weekday as number between 0 and 6, with 0 meaning "Sunday"  
dt - as.numeric(strftime(dt, format="%w"))
#  [1] "2016-10-16" "2016-10-09" "2016-10-09" "2016-10-09" "2016-10-09"
#  [6] "2016-10-09" "2016-10-09" "2016-10-09" "2016-10-02" "2016-10-02"
# [11] "2016-10-02" "2016-10-02" "2016-10-02" "2016-10-02" "2016-10-02"
# [16] "2016-09-25" "2016-09-25" "2016-09-25" "2016-09-25" "2016-09-25"
Run Code Online (Sandbox Code Playgroud)