【发布时间】:2020-06-07 07:58:08
【问题描述】:
我有一个每个客户在不同时间被传感器捕获的数据集。因此客户将进入商店,并且将通过 sensor_id 1 捕获,并且客户也可以通过 sensor_id 2 进入。但是客户只能通过sensor_id 3.数据集如下:
library(data.table)
library(lubridate)
DT1 <- data.table(
customer_id=c(1,1,1,2,2,2,1,1),
sensor_id=c(1,2,3,1,2,3,2,3),
in_time=c("2017-01-01 00:00:05","2017-01-01 00:06:35","2017-01-01 00:23:44","2017-01-02 22:00:20","2017-01-02 22:01:09","2017-01-02 22:28:02","2017-01-03 22:23:01","2017-01-03 22:50:52")
)
DT1[,in_time:=ymd_hms(in_time)]
所以从这里,我想得到数据框
result <- data.table(
customer_id=c(1,2,1),
entry_sensor_id=c(1,1,2),
entry_time=c("2017-01-01 00:00:05","2017-01-02 22:00:20","2017-01-03 22:23:01"),
entry_sensor_id=c(3,3,3),
exit_Time=c("2017-01-01 00:23:44","2017-01-02 22:28:02","2017-01-03 22:50:52")
)
所以我尝试了以下方法:
DT1[, spotted_group := rleid( cumsum(difftime(in_time,
shift(in_time, fill = first(in_time)), units = "mins") > 120)), customer_id]
DT1Stretch=DT1[ DT1[order(in_time), .I[c(1L,.N)], by=list(customer_id,spotted_group)]$V1 ]
DT1Stretch[,c(.SD[1,] , .SD[2,]),by=c("customer_id","spotted_group")]
但是如果客户在 2 小时内返回商店,这种方法将不起作用,因为我根据 120 分钟的差异标记了 Spotted_group,这并不理想。
不确定哪种方法是解决我的问题的正确方法。任何帮助表示赞赏。
给留在店里和得到的顾客的群体贴上标签
【问题讨论】:
标签: r dplyr data.table