从给定的一天开始一周并在 R 中获取周数
Start a week from given day and get week number in R
让我们有一个日期序列,
df = data.frame(date = seq(as.Date('2022-01-01'),as.Date('2022-01-31'),by = 1))
我想从 星期二 开始一周,然后削减日期以创建新列 week
给出周数。所需的输出是,
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
同样,如果我想从星期三开始一周,预期输出是,
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
我该如何完成?
如果一周从星期一开始,我会使用,
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
感谢您的帮助...
我们可以在 floor_date
中指定 week_start
(week_start
- 1
将是 Monday
而 7
将是 Sunday
)
f1 <- function(dates, wk_start = 1) {
new <- lubridate::floor_date(dates, 'week', week_start = wk_start)
match(new, unique(new))
}
-正在检查
> 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
让我们有一个日期序列,
df = data.frame(date = seq(as.Date('2022-01-01'),as.Date('2022-01-31'),by = 1))
我想从 星期二 开始一周,然后削减日期以创建新列 week
给出周数。所需的输出是,
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
同样,如果我想从星期三开始一周,预期输出是,
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
我该如何完成?
如果一周从星期一开始,我会使用,
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
感谢您的帮助...
我们可以在 floor_date
中指定 week_start
(week_start
- 1
将是 Monday
而 7
将是 Sunday
)
f1 <- function(dates, wk_start = 1) {
new <- lubridate::floor_date(dates, 'week', week_start = wk_start)
match(new, unique(new))
}
-正在检查
> 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