I have a dataframe of a service. Now I need to add a column "order" and group them with the following rule:
Group the service to orders: If within the next 5 values after one service Value "A" is another service "A" present, fill all values to an order ID - also the ones that don't have a service value. If there is no service value within the next 5 values the next order group is defined.
id time apples service
1 13:20:01 2
2 13:20:02 2 A
3 13:20:03 2 A
4 13:20:04 3
5 13:20:05 3 A
6 13:20:06 2
7 13:20:07 2 A
8 13:20:08 2 A
9 13:20:09 2
10 13:20:10 2
11 13:20:11 2
12 13:20:12 2
14 13:20:13 2 A
15 13:20:14 2
16 13:20:15 2 A
This is the format I'm looking for. ID 2 to ID 8 is an order and ID 14 to ID 16.
id time apples service Order
1 13:20:01 2
2 13:20:02 2 A 1
3 13:20:03 2 A 1
4 13:20:04 3 1
5 13:20:05 3 A 1
6 13:20:06 2 1
7 13:20:07 2 A 1
8 13:20:08 2 A 1
9 13:20:09 2
10 13:20:10 2
11 13:20:11 2
12 13:20:12 2
14 13:20:13 2 A 2
15 13:20:14 2 2
16 13:20:15 2 A 2
I tried it with a for loop. I suggests there is a way to use the mutate method and add the "range" conditon.
Thx for your help!
Aucun commentaire:
Enregistrer un commentaire