【发布时间】:2022-02-10 00:06:57
【问题描述】:
我想使用 lubridate R 包将日期转换为以月为单位的周和两周。我的工作示例如下:
library(tidyverse)
library(lubridate)
dt1 <-
tibble(
Date = seq(from = ymd("2021-01-01"), to = ymd("2021-12-31"), by = '1 day')
, Week = week(Date)
, Fortnight = ceiling(week(Date)/2)
, Month = month(Date)
)
dt2 <-
dt1 %>%
group_by(Month) %>%
mutate(
WK = week(Date)
, FN = ceiling(week(Date)/2)
)
head(dt2, 10)
# A tibble: 10 x 6
# Groups: Month [1]
Date Week Fortnight Month WK FN
<date> <dbl> <dbl> <dbl> <dbl> <dbl>
1 2021-01-01 1 1 1 1 1
2 2021-01-02 1 1 1 1 1
3 2021-01-03 1 1 1 1 1
4 2021-01-04 1 1 1 1 1
5 2021-01-05 1 1 1 1 1
6 2021-01-06 1 1 1 1 1
7 2021-01-07 1 1 1 1 1
8 2021-01-08 2 1 1 2 1
9 2021-01-09 2 1 1 2 1
10 2021-01-10 2 1 1 2 1
tail(dt2, 10)
# A tibble: 10 x 6
# Groups: Month [1]
Date Week Fortnight Month WK FN
<date> <dbl> <dbl> <dbl> <dbl> <dbl>
1 2021-12-22 51 26 12 51 26
2 2021-12-23 51 26 12 51 26
3 2021-12-24 52 26 12 52 26
4 2021-12-25 52 26 12 52 26
5 2021-12-26 52 26 12 52 26
6 2021-12-27 52 26 12 52 26
7 2021-12-28 52 26 12 52 26
8 2021-12-29 52 26 12 52 26
9 2021-12-30 52 26 12 52 26
10 2021-12-31 53 27 12 53 27
问题
- WK(按月计算的周数)和 FT(按月计算的两周)与预期不同。
- 想要将周标记为 1 月 1 日至 07 日、1 月 08 日至 14 日、1 月 15 日至 21 日、1 月 22 日至 28 日、1 月 29 日至 31 日等。
- 想要将双周标记为 1 月 1 日至 14 日、1 月 15 日至 28 日、1 月 29 日至 31 日等。
【问题讨论】:
标签: r date tidyverse lubridate