12

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.

Community
  • 1
  • 1
krish
  • 1,388
  • 2
  • 18
  • 28

2 Answers2

32

Use the floor_date function from the lubridate package.

library("lubridate")
floor_date(as.Date("04/20/2017", "%m/%d/%Y"), unit="week")
Khaynes
  • 1,976
  • 2
  • 15
  • 27
Vamsi Prabhala
  • 48,685
  • 4
  • 36
  • 58
9

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"
Erdem Akkas
  • 2,062
  • 10
  • 15
  • I'm not sure whether it's an issue with how `format` works or just its use here, but this doesn't work for all dates; for example, `as.Date(format(as.Date("01/04/2019", "%m/%d/%Y"),"%Y-%W-1"),"%Y-%W-%u")` returns `NA` because `format(as.Date("01/04/2019", "%m/%d/%Y"),"%Y-%W-1")` returns `"2019-00-1"`. – Rookatu Nov 22 '19 at 23:24