使用 dplyr 和 lurbridate 创建几天的偏移间隔

Creating offset intervals for days with dplyr and lurbridate

我正在尝试使用 dplyr 和 lubridate 创建一个“24 小时”的一天,从 07:00:00 开始到 06:59:59 结束,我可以用它来捕捉排的重叠一天。我尝试了几种方法,尝试分组并使用 int_difffloor_date() + 24,并且我正在努力让这个新变量发挥作用。例如,我需要 2020-01-01 10:00:002020-01-02 05:47:49 来标识“第 1 天”,但需要 2020-01-02 07:00:01 来标识“第 2 天”,等等。

df_ex
   platoon_id           disp_time
1   PLATOON 1 2020-01-01 10:06:48
2   PLATOON 1 2020-01-01 12:56:57
3   PLATOON 2 2020-01-02 07:10:30
4   PLATOON 2 2020-01-02 09:31:28
5   PLATOON 2 2020-01-02 09:45:00
6   PLATOON 2 2020-01-02 10:11:58
7   PLATOON 2 2020-01-02 10:59:09
8   PLATOON 2 2020-01-02 14:56:57
9   PLATOON 2 2020-01-03 07:45:51
10  PLATOON 3 2020-01-03 09:20:35
11  PLATOON 3 2020-01-03 10:12:29
12  PLATOON 3 2020-01-03 10:54:31
13  PLATOON 3 2020-01-03 12:55:40
14  PLATOON 3 2020-01-03 15:19:03
15  PLATOON 3 2020-01-03 16:11:51
16  PLATOON 3 2020-01-03 18:15:51
17  PLATOON 3 2020-01-03 20:39:32
18  PLATOON 3 2020-01-03 21:26:53
19  PLATOON 3 2020-01-04 03:11:38
20  PLATOON 3 2020-01-04 06:48:16
21  PLATOON 4 2020-01-04 10:27:57
22  PLATOON 4 2020-01-04 10:43:37
23  PLATOON 4 2020-01-04 19:53:20
24  PLATOON 4 2020-01-05 03:24:08
25  PLATOON 4 2020-01-05 04:22:13

如有任何帮助,我们将不胜感激!

library(magrittr)
df_ex %>%
  dplyr::mutate(day_number = lubridate::yday(disp_time) - (lubridate::hour(disp_time) < 7))

我认为上面的代码为您提供了一个新变量,day_number 对应于您想要的日期。

首先,我使用加载包 magrittr,这样我就可以使用管道 %>%。然后,我将您的数据框“管道”到函数 mutate(在 dplyr 包中)。 mutate 采用现有数据框并创建一个新变量,在本例中为 day_number,由等式的 right-hand 端定义。如果我们只想要每天的数字(年份),那么我们就此止步。但是,您需要 7 小时的偏移量。换句话说,1 月 2 日早上 6 点应该 return 第 1 天,而 1 月 2 日早上 8 点应该 return 第 2 天。更准确地说,第 X 天早上 7 点之前的任何时间都应该 return 第 X 天-1。远 right-hand 一侧的括号,(lubridate::hour(disp_time) < 7) return 是 TRUE 还是 FALSE,具体取决于断言的真实性,即一天中的时间小于早上 7 点。 R 然后将 TRUE(或 FALSE)强制转换为 1(或 0),并从 right-hand 边的第一部分减去该数量,lubridate::yday(disp_time).

:: 对某些读者来说可能很陌生。它允许我从命名空间(或包)调用导出的函数。所以,lubridate::yday 指的是包 lubridate.

中的函数 yday

管道,%>%,我发现在处理数据框时特别有用。您可以在免费在线书籍“R for data science”中阅读更多相关信息:https://r4ds.had.co.nz/