如何分别标记所有组记录?

问题描述 投票:0回答:1

所以我要记录每个人在每个商店中发现的时间,我想根据时差是5分钟或新的商店ID来对组进行不同的标记。数据如下:

  DT1<-data.table(
  id=c(1,1,1,1,1,1,1,1),
  in_time=c("2017-11-01 08:37:35","2017-11-01 08:38:42","2017-11-01 08:39:45","2017-11-01 08:50:35","2017-11-01 08:51:35","2017-11-01 08:52:44","2017-11-01 08:53:16","2017-11-01 08:59:29"),
  store_id=c(1,1,1,1,1,2,2,2)

  )
  DT1[,in_time:=ymd_hms(in_time)]

然后,我使用下面的代码将每个组分开。

DT1[,group:= cumsum(difftime(in_time, shift(in_time, fill=-Inf), units="mins") > 5), by=list(id,store_id)]

但是随后我又以​​相同的ID获得了相同的组。有什么方法可以为不同的组获取不同的组ID(您可以看到组1在2017-11-01 08:52:44再次重复)。另外,我有多个ID,这就是为什么我按ID和存储ID进行分组。

感谢您的任何帮助。

r dplyr data.table shift
1个回答
0
投票
您可以尝试使用rleid获得唯一索引并在其中包含store_id

library(data.table) DT1[, group := rleid(store_id, cumsum(difftime(in_time, shift(in_time, fill = first(in_time)), units = "mins") > 5)), id] DT1 # id in_time store_id group #1: 1 2017-11-01 08:37:35 1 1 #2: 1 2017-11-01 08:38:42 1 1 #3: 1 2017-11-01 08:39:45 1 1 #4: 1 2017-11-01 08:50:35 1 2 #5: 1 2017-11-01 08:51:35 1 2 #6: 1 2017-11-01 08:52:44 2 3 #7: 1 2017-11-01 08:53:16 2 3 #8: 1 2017-11-01 08:59:29 2 4

© www.soinside.com 2019 - 2024. All rights reserved.