How to round floor_date() to arbitrary date?

可紊 提交于 2020-01-16 12:21:47

问题


I am using floor_date to round dates to the weeks:

library(lubridate)
floor_date(ymd_hms('2016-08-26 16:27:15'), '7 days')
[1] "2016-08-22 UTC"

However, I would like to set a specific date as the beginning of the first week. For instance, I would like to set "2016-08-26 UTC" as first week. As a workaround I was trying to tweak getOption("lubridate.week.start"), but I cannot get to change the starting weekday regardless of what I pass:

> floor_date(ymd_hms('2016-08-26 16:27:15'), '7 days', week_start = getOption("lubridate.week.start", 1))
[1] "2016-08-22 UTC"
> floor_date(ymd_hms('2016-08-26 16:27:15'), '7 days', week_start = getOption("lubridate.week.start", 7))
[1] "2016-08-22 UTC"

回答1:


You need to set unit = "week". From ?round_date

week_start: when unit is weeks specify the reference day; 7 being Sunday.

Example

library(lubridate)
lapply(c(1, 5), function(x) floor_date(ymd('2016-08-26'), 'week', week_start = x))
#[[1]]
#[1] "2016-08-22"
#
#[[2]]
#[1] "2016-08-26"


来源:https://stackoverflow.com/questions/48735472/how-to-round-floor-date-to-arbitrary-date

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!