按日期范围在 R 中分配值

Assigning Values in R by Date Range

我正在尝试在我的日常观察数据集中创建一个“周”变量,每当新的星期一发生时,它都以新值(1、2、3 等)开头。我的数据集有从 2020 年 4 月 6 日开始的观测数据,数据以“YYYY-MM-DD”as.date() 格式存储。在此示例中,4 月 6 日至 4 月 12 日之间的观察结果为“1”,4 月 13 日至 4 月 19 日之间的观察结果为“2”,等等。

我知道 lubridate 中的 week() 包,但不幸的是,这对我的目的不起作用,因为一年中不完全是 54 周,因此“第 54 周”只是一个几天之久。换句话说,我想将2020年12月28日到2021年1月3日归为同一周。

有没有人有解决这个问题的好方法?我很感激人们可能有的任何见解。

减去具有最小日期的日期,将差值除以 7,然后使用 floor 每 7 天得到 1 个数字。

x <- as.Date(c('2020-04-06','2020-04-07','2020-04-13','2020-12-28','2021-01-03'))
as.integer(floor((x - min(x))/7) + 1)
#[1]  1  1  2 39 39

也许 lubridate::isoweek()lubridate::isoyear() 是您想要的?

一些数据:

df1 <- data.frame(date = seq.Date(as.Date("2020-04-06"), 
                                  as.Date("2021-01-04"), 
                  by = "1 day"))

示例代码:

library(dplyr)
library(lubridate)

df1 <- df1 %>% 
  mutate(week = isoweek(date), 
  year = isoyear(date)) %>% 
  group_by(year) %>% 
  mutate(week2 = 1 + (week - min(week))) %>% 
  ungroup()

head(df1, 8)

# A tibble: 8 x 4
  date        week  year week2
  <date>     <dbl> <dbl> <dbl>
1 2020-04-06    15  2020     1
2 2020-04-07    15  2020     1
3 2020-04-08    15  2020     1
4 2020-04-09    15  2020     1
5 2020-04-10    15  2020     1
6 2020-04-11    15  2020     1
7 2020-04-12    15  2020     1
8 2020-04-13    16  2020     2

tail(df1, 8)

# A tibble: 8 x 4
  date        week  year week2
  <date>     <dbl> <dbl> <dbl>
1 2020-12-28    53  2020    39
2 2020-12-29    53  2020    39
3 2020-12-30    53  2020    39
4 2020-12-31    53  2020    39
5 2021-01-01    53  2020    39
6 2021-01-02    53  2020    39
7 2021-01-03    53  2020    39
8 2021-01-04     1  2021     1

这也行

df <- data.frame(date = as.Date("2020-04-06")+ 0:365)

library(dplyr)
library(lubridate)

df %>% group_by(d= year(date), week = (isoweek(date))) %>%
  mutate(week = cur_group_id()) %>% ungroup() %>% select(-d)

# A tibble: 366 x 2
   date        week
   <date>     <int>
 1 2020-04-06     1
 2 2020-04-07     1
 3 2020-04-08     1
 4 2020-04-09     1
 5 2020-04-10     1
 6 2020-04-11     1
 7 2020-04-12     1
 8 2020-04-13     2
 9 2020-04-14     2
10 2020-04-15     2
# ... with 356 more rows