How to get week starting date from a date in R [duplicate]

不问归期 提交于 2019-12-05 03:42:42

问题


I have a dataset with a column containing dates. I want to find the week starting dates for those date values.

I get the week number using week function from lubridate. For example,

week(as.Date("04/20/2017", "%m/%d/%Y"))

#Solution
[1] 16

Instead of weeknum, is there a way to get the starting date of the week? In this case I am expecting either "04/16/2017" or "04/17/2017". I am not very particular if the week starts from Sunday or Monday. I looked at this question, but didn't get much from it.


回答1:


Use floor_date function.

floor_date(as.Date("04/20/2017", "%m/%d/%Y"), unit="week")



回答2:


You can use below

as.Date(format(as.Date("04/20/2017", "%m/%d/%Y"),"%Y-%W-1"),"%Y-%W-%u")
[1] "2017-04-17"


来源:https://stackoverflow.com/questions/43521371/how-to-get-week-starting-date-from-a-date-in-r

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