如何只对群组进行一次编号......并重复一次?
我有以下内容:
vehicle stop_time
Truck53 0:16:34
Truck53 0:18:06
Truck12 0:12:04
Truck12 0:16:32
Truck12 0:17:40
Truck65 0:13:22
Truck65 0:14:38
Truck65 0:15:43
Truck35 0:14:17
Truck35 0:17:37
Truck35 0:20:31
Truck39 0:15:04
Truck39 0:19:45
Truck39 0:22:10
Truck99 0:16:12
Truck59 0:17:44
Truck59 0:20:39
但是,一次只能有2辆卡车离开,所以我必须通过每2辆卡车反复计算一次来给他们一个波浪:
vehicle stop_time wave_id
Truck53 0:16:34 1
Truck53 0:18:06 1
Truck12 0:12:04 1
Truck12 0:16:32 1
Truck12 0:17:40 1
Truck65 0:13:22 2
Truck65 0:14:38 2
Truck65 0:15:43 2
Truck35 0:14:17 2
Truck35 0:17:37 2
Truck35 0:20:31 2
Truck39 0:15:04 3
Truck39 0:19:45 3
Truck39 0:22:10 3
Truck99 0:16:12 3
Truck59 0:17:44 4
Truck59 0:20:39 4
答案 0 :(得分:1)
可能的解决方案:
uv <- unique(df$vehicle)
df$wave_id <- ((seq_along(uv) + 1) %/% 2)[match(df$vehicle, uv)]
给出:
> df vehicle stop_time wave_id 1 Truck53 0:16:34 1 2 Truck53 0:18:06 1 3 Truck12 0:12:04 1 4 Truck12 0:16:32 1 5 Truck12 0:17:40 1 6 Truck65 0:13:22 2 7 Truck65 0:14:38 2 8 Truck65 0:15:43 2 9 Truck35 0:14:17 2 10 Truck35 0:17:37 2 11 Truck35 0:20:31 2 12 Truck39 0:15:04 3 13 Truck39 0:19:45 3 14 Truck39 0:22:10 3 15 Truck99 0:16:12 3 16 Truck59 0:17:44 4 17 Truck59 0:20:39 4
这是做什么的:
unique(df$vehicle)
,您可以创建唯一卡车ID的矢量。((seq_along(uv) + 1) %/% 2)
,您可以将卡车分组为两辆卡车(最后一组只需一辆卡车):1 1 2 2 3 3 4
match(mydf$vehicle, uv)
创建前一个向量的位置向量。df