Home > Back-end >  lubridate: Finding weeks within months
lubridate: Finding weeks within months

Time:02-10

I want to find weeks within months (separate numbering of weeks within months) using lubridate R package. My minimum working example is below:

library(tidyverse)
library(lubridate)
dt1 <- 
  tibble(
    Date  = seq(from = ymd("2021-01-01"), to = ymd("2021-12-31"), by = '1 day')
  , Month = month(Date)
    )

dt2 <-
  dt1 %>% 
  group_by(Month) %>% 
  mutate(Week = week(Date))

dt2 %>% 
  print(n = 40)

# A tibble: 365 x 3
# Groups:   Month [12]
   Date       Month  Week
   <date>     <dbl> <dbl>
 1 2021-01-01     1     1
 2 2021-01-02     1     1
 3 2021-01-03     1     1
 4 2021-01-04     1     1
 5 2021-01-05     1     1
 6 2021-01-06     1     1
 7 2021-01-07     1     1
 8 2021-01-08     1     2
 9 2021-01-09     1     2
10 2021-01-10     1     2
11 2021-01-11     1     2
12 2021-01-12     1     2
13 2021-01-13     1     2
14 2021-01-14     1     2
15 2021-01-15     1     3
16 2021-01-16     1     3
17 2021-01-17     1     3
18 2021-01-18     1     3
19 2021-01-19     1     3
20 2021-01-20     1     3
21 2021-01-21     1     3
22 2021-01-22     1     4
23 2021-01-23     1     4
24 2021-01-24     1     4
25 2021-01-25     1     4
26 2021-01-26     1     4
27 2021-01-27     1     4
28 2021-01-28     1     4
29 2021-01-29     1     5
30 2021-01-30     1     5
31 2021-01-31     1     5
32 2021-02-01     2     5
33 2021-02-02     2     5
34 2021-02-03     2     5
35 2021-02-04     2     5
36 2021-02-05     2     6
37 2021-02-06     2     6
38 2021-02-07     2     6
39 2021-02-08     2     6
40 2021-02-09     2     6
# ... with 325 more rows

Wondering what am I missing here. For row number 31 in output (31 2021-01-31 1 5), the value in Week column should be 1. Any lead to get the desired output.

CodePudding user response:

It's not completely clear how you are defining a week. If Week 1 starts on the first day of a month, then you can do:

dt2 <- dt1 %>% mutate(Week = 1L   ((day(Date) - 1L) %/% 7L))
dt2 %>% slice(21:40) %>% print(n = 20L)
# A tibble: 20 × 3
   Date       Month  Week
   <date>     <dbl> <int>
 1 2021-01-21     1     3
 2 2021-01-22     1     4
 3 2021-01-23     1     4
 4 2021-01-24     1     4
 5 2021-01-25     1     4
 6 2021-01-26     1     4
 7 2021-01-27     1     4
 8 2021-01-28     1     4
 9 2021-01-29     1     5
10 2021-01-30     1     5
11 2021-01-31     1     5
12 2021-02-01     2     1
13 2021-02-02     2     1
14 2021-02-03     2     1
15 2021-02-04     2     1
16 2021-02-05     2     1
17 2021-02-06     2     1
18 2021-02-07     2     1
19 2021-02-08     2     2
20 2021-02-09     2     2

With base R, you could simply do:

Week <- 1L   ((as.POSIXlt(Date)$mday - 1L) %/% 7L)
  • Related