lubridate:在几个月内找到几周

lubridate: Finding weeks within months

我想使用 lubridate R 包查找月内的周数(月内的周数单独编号)。我的最低工作示例如下:

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

想知道我在这里错过了什么。对于输出 (31 2021-01-31 1 5) 中的行号 31Week 列中的值应为 1。获得所需输出的任何线索。

您对一周的定义并不完全清楚。如果第 1 周从一个月的第一天开始,那么您可以:

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

使用基础 R,你可以简单地做:

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