mardi 18 octobre 2016

Loop/if else in R for data frame

I am really stuck on doing a loop in R. I have tried using ifelse too, but just can't seem to get a result.

I have a data frame as follows which shows a customer ID, their date of travel, mode and journey start time:

ID     |  Date     |   Mode  |  Time
------ | --------- | ------- | -----
1234   | 12/10/16  | Bus     |  120 
1234   | 12/10/16  | Bus     |  130
1234   | 12/10/16  | Bus     |  290
1234   | 12/10/16  | Train   |  310
1234   | 12/10/16  | Bus     |  330
4567   | 12/10/16  | Bus     |  220 
4567   | 12/10/16  | Bus     |  230
4567   | 13/10/16  | Bus     |  290
4567   | 13/10/16  | Bus     |  450
4567   | 14/10/16  | Train   |  1000

So on 12/10, customer 1234 made 4 bus jnys and 2 train jnys.

I want to create a 5th column which identifies if the journey stages are linked i.e. is the 2nd journey linked to the 1st journey, is the 3rd journey linked to the 2nd journey (where 1=linked, 0=not linked).

The following conditions need to apply:

  • the jnys are for the same person and take place on the same day

  • 2 bus journeys are within 60 mins of one another (so a bus and train journey within 60 mins of one another would not be linked)

  • if the i+1th and the ith journey are linked, then the i+1th journey cannot be linked to the i+2th journey

I would like the output to be as follows:

ID     |  Date     |   Mode  |  Time  | Linked
------ | --------- | ------- | -----  | -----
1234   | 12/10/16  | Bus     |  120   |  0
1234   | 12/10/16  | Bus     |  130   |  1
1234   | 12/10/16  | Bus     |  290   |  0
1234   | 12/10/16  | Train   |  310   |  0
1234   | 12/10/16  | Bus     |  330   |  0
4567   | 12/10/16  | Bus     |  220   |  0
4567   | 12/10/16  | Bus     |  230   |  1
4567   | 13/10/16  | Bus     |  290   |  0
4567   | 13/10/16  | Bus     |  450   |  0
4567   | 14/10/16  | Train   |  1000  |  0

Any help would be much appreciated!

Aucun commentaire:

Enregistrer un commentaire