在分组但不汇总的基础上,根据条件计算持续时间

时间:2020-03-31 21:06:28

标签: r dplyr tidyverse

目标:

我有一个数据集df,我想对ID进行分组并根据以下条件找到持续时间:Focus == True,Read == True,ID!=“”。但是,我不想汇总ID,因为我希望将它们放在自己的单独“块”中

ID            Date                   Focus        Read


A             1/2/2020 5:00:00 AM    True         True
A             1/2/2020 5:00:05 AM    True         True
              1/3/2020 6:00:00 AM    True
              1/3/2020 6:00:05 AM    True         
B             1/4/2020 7:00:00 AM    True         True
B             1/4/2020 7:00:02 AM    True         True
B             1/4/2020 7:00:10 AM    True         True
A             1/2/2020 7:30:00 AM    True         True
A             1/2/2020 7:30:20 AM    True         True

我想要以下输出:

ID                          Duration               Date

A                           5 sec                  1/2/2020
B                           10 sec                 1/4/2020
A                           20 sec                 1/2/2020

投放:

structure(list(ID = structure(c(2L, 2L, 1L, 1L, 3L, 3L, 3L, 2L, 
2L), .Label = c("", "A", "B"), class = "factor"), Date = structure(c(1L, 
2L, 5L, 6L, 7L, 8L, 9L, 3L, 4L), .Label = c("1/2/2020 5:00:00 AM", 
"1/2/2020 5:00:05 AM", "1/2/2020 7:30:00 AM", "1/2/2020 7:30:20 AM", 
"1/3/2020 6:00:00 AM", "1/3/2020 6:00:05 AM", "1/4/2020 7:00:00 AM", 
"1/4/2020 7:00:02 AM", "1/4/2020 7:00:10 AM"), class = "factor"), 
Focus = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = "True ", class = "factor"), 
Read = structure(c(2L, 2L, 1L, 1L, 2L, 2L, 2L, 2L, 2L), .Label = c("", 
"True "), class = "factor")), class = "data.frame", row.names = c(NA, 
-9L))

这很好用,但是我不汇总ID,而是将它们分开:

 library(dplyr)
 library(lubridate)
 df %>% 
 filter(as.logical(trimws(Read)), as.logical(trimws(Focus))) %>%
 mutate(Date = mdy_hms(Date)) %>%
 group_by(ID) %>% 
 summarise(Duration = difftime(last(Date), first(Date), units = "secs"))

任何建议都值得赞赏。

1 个答案:

答案 0 :(得分:1)

我们可以为'ID'中的相邻非等号元素创建带有run-length-encoding-id rleid的组,然后将difftime应用于转换为{ {1}}

DateTime