我有一个csv格式的事件日志,并希望在表中指定具有特定条件的单元格。该表如下所示。
Case.ID | Activity | Timestamp | Resource
----------------------------------------------
0 |Take order| 00:12:04 | Waiter
----------------------------------------------
0 |Take order| 00:18:02 |
----------------------------------------------
1 |Bring food| 00:47:23 | Cook helper
----------------------------------------------
1 |Bring food| 00:52:41 |
活动的开始在资源列中具有值,但活动的结尾没有。
我想创建一个列持续时间,这是从结束时间戳到开始时间戳的差异,但不知道如何处理它。
答案 0 :(得分:1)
如果你强迫你的因子成为一个字符变量,你可以尝试:
library(tidyverse)
df = data.frame(Case.ID = c(0,0,1,1),
Activity = c(rep("Take order",2),rep("Bring food",2)),
Timestamp = c("00:12:04","00:18:02","00:47:23","00:52:41"),
Resource = c("Waiter","","Cook helper",""),stringsAsFactors = F)
df %>% group_by(Case.ID) %>% mutate(timing = as.difftime(Timestamp[length(Timestamp)])-as.difftime(Timestamp[1]))
不是那么优雅,因为它重复了行的值,但我不确定你的目标是什么
答案 1 :(得分:0)
使用@timfaber提供的数据框:
aggregate(x = list(duration = as.POSIXct(df$Timestamp,format = "%H:%M:%S")),
by = list(Case.ID = df$Case.ID),
FUN = diff)
这给出了:
Case.ID duration
1 0 5.966667
2 1 5.300000