R 计算两个日期时间之间15分钟的序列发生时间
我有一个日期时间表,希望在00:00到00:00的时间内为每行添加一个新的数据帧,顺序为15分钟,例如00:00,00:15。。。23:45我试图找出一个工人在其日程表中工作的次数 请注意,日期时间格式为R 计算两个日期时间之间15分钟的序列发生时间,r,datetime,R,Datetime,我有一个日期时间表,希望在00:00到00:00的时间内为每行添加一个新的数据帧,顺序为15分钟,例如00:00,00:15。。。23:45我试图找出一个工人在其日程表中工作的次数 请注意,日期时间格式为d-m-Y h:m 我已(更改为我的数据) 我希望在这个输出中有一个新的数据帧。在那里我可以看到它们在不同的时间戳中工作了多少 这只是所需输出的一个示例,而不是上述数据集的真实输出。下面的计数可能是错误的 00:00 | 00:15 | 00:30 | ... | 23:
d-m-Y h:m
我已(更改为我的数据)
我希望在这个输出中有一个新的数据帧。在那里我可以看到它们在不同的时间戳中工作了多少
这只是所需输出的一个示例,而不是上述数据集的真实输出。下面的计数可能是错误的
00:00 | 00:15 | 00:30 | ... | 23:45
worker 130 5 5 6 .. 4
worker 18 2 5 5 .. 3
worker 11 1 1 1 .. 1
我尝试用seq()调用创建一个15分钟的序列
seq15我正在使用您发布为dt
的数据:
library(tidyverse)
library(lubridate)
dt %>%
mutate(Start_shift = dmy_hm(Start_shift),
End_shift = dmy_hm(End_shift)) %>% # update to datetime
rowwise() %>% # for each row
mutate(date_vec = list(seq(Start_shift,
End_shift,
by = "15 mins"))) %>% # create a vector of 15 min distance date-times
ungroup() %>% # forget the grouping
unnest() %>% # unnest vector of date-times
mutate(time = substr(date_vec, 12,16)) %>% # keep only hr-mins
count(worker, time) %>% # count combinations
spread(time, n) # reshape
还有一种更紧凑的替代解决方案,它使用map
替换rowwise
,同时生成日期-时间向量并保持hr分钟数:
dt %>%
mutate(Start_shift = dmy_hm(Start_shift),
End_shift = dmy_hm(End_shift),
time = map2(Start_shift, End_shift, ~substr(seq(.x, .y, by = "15 mins"), 12, 16))) %>%
unnest(time) %>%
count(worker, time) %>%
spread(time, n)
使用dput(d)
,其中d
是数据集的一个小样本。一个很好的例子是df=mtcars[1:3,];dput(df)
然后将dput
返回的内容复制并粘贴到控制台上您的问题下。您确定所需的数据集是正确的吗?例如,为什么worker 18为00:15
设置了1
?我们可以轻松添加一个过程来删除重复项。但是,首先,您需要检查流程是否仅使用您首先发布的示例数据成功运行。不是完整的数据集,因为这样更容易发现任何错误。如果这样行的话,你就可以使用完整的数据。如果你来丹麦、哥本哈根,我会给你买一杯啤酒!
library(tidyverse)
library(lubridate)
dt %>%
mutate(Start_shift = dmy_hm(Start_shift),
End_shift = dmy_hm(End_shift)) %>% # update to datetime
rowwise() %>% # for each row
mutate(date_vec = list(seq(Start_shift,
End_shift,
by = "15 mins"))) %>% # create a vector of 15 min distance date-times
ungroup() %>% # forget the grouping
unnest() %>% # unnest vector of date-times
mutate(time = substr(date_vec, 12,16)) %>% # keep only hr-mins
count(worker, time) %>% # count combinations
spread(time, n) # reshape
dt %>%
mutate(Start_shift = dmy_hm(Start_shift),
End_shift = dmy_hm(End_shift),
time = map2(Start_shift, End_shift, ~substr(seq(.x, .y, by = "15 mins"), 12, 16))) %>%
unnest(time) %>%
count(worker, time) %>%
spread(time, n)