Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Start a week from given day and get week number in R

Lets have a sequence of dates,

df  = data.frame(date = seq(as.Date('2022-01-01'),as.Date('2022-01-31'),by = 1))

I want to start the week from Tuesday and then cut the dates to create new column week giving the week number. Required output is,

date           week
1  2022-01-01    1
2  2022-01-02    1
3  2022-01-03    1
4  2022-01-04    2
5  2022-01-05    2

Similarly, if I wanted to start the week from Wednesday the expected output is,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

date           week
1  2022-01-01    1
2  2022-01-02    1
3  2022-01-03    1
4  2022-01-04    1
5  2022-01-05    2
6  2022-01-06    2

How can I get this done?

If the week were to start from Monday I would have used,

df%>% mutate(week = cut.Date(df$date, breaks = "1 week", labels = FALSE)) 
        date week
1  2022-01-01    1
2  2022-01-02    1
3  2022-01-03    2
4  2022-01-04    2
5  2022-01-05    2

Thank you for any help…

>Solution :

We may specify the week_start in floor_date (week_start1 would be Monday and 7 would be Sunday)

f1 <- function(dates, wk_start = 1) {
    new <- lubridate::floor_date(dates, 'week', week_start = wk_start)
    match(new, unique(new))
}

-checking

> library(dplyr)
> df %>%
+    mutate(week = f1(date, wk_start = 1)) %>%
+    head
        date week
1 2022-01-01    1
2 2022-01-02    1
3 2022-01-03    2
4 2022-01-04    2
5 2022-01-05    2
6 2022-01-06    2
> df %>%
+    mutate(week = f1(date, wk_start = 2)) %>%
+    head
        date week
1 2022-01-01    1
2 2022-01-02    1
3 2022-01-03    1
4 2022-01-04    2
5 2022-01-05    2
6 2022-01-06    2
> df %>%
+    mutate(week = f1(date, wk_start = 3)) %>%
+    head
        date week
1 2022-01-01    1
2 2022-01-02    1
3 2022-01-03    1
4 2022-01-04    1
5 2022-01-05    2
6 2022-01-06    2
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading