How to use mutate to create a variable that will give me a the dates for a week in R?

Viewed 219

this is my data. my dates are in year-month-day format

Date
2020-01-02 
2020-01-05
2020-01-07
2020-01-08
2020-01-10
2020-01-15
2020-01-16

I want to create a new column that will tell me what range of dates of that falls on that follows the calendar system.

Date             Range
2020-01-02       01/01-01/03
2020-01-05       01/05-01/11
2020-01-07       01/05-01/11
2020-01-08       01/05-01/11
2020-01-10       01/05-01/11
2020-01-15       01/12-01/18
2020-01-16       01/12-01/18

How can i do this?

1 Answers

Here is one approach using floor_date and ceiling_date from lubridate. In this example, an interval is created with a date range, from Sunday to Saturday.

library(lubridate)
library(dplyr)

df %>%
  mutate(Range = interval(
    floor_date(Date, "week"),
    ceiling_date(Date, "week") - 1
  ))

Output

        Date                          Range
1 2020-01-02 2019-12-29 UTC--2020-01-04 UTC
2 2020-01-05 2020-01-05 UTC--2020-01-11 UTC
3 2020-01-07 2020-01-05 UTC--2020-01-11 UTC
4 2020-01-08 2020-01-05 UTC--2020-01-11 UTC
5 2020-01-10 2020-01-05 UTC--2020-01-11 UTC
6 2020-01-15 2020-01-12 UTC--2020-01-18 UTC
7 2020-01-16 2020-01-12 UTC--2020-01-18 UTC
Related