lundi 19 juin 2017

Combining rows which meet a criterion in R

I have a standard data frame where I have individuals doing a certain behavior over a period of time. When an incident occurs within 50 seconds of the previous incident (Delay <=50) I would like to combine it with the previous incident. That is, each incident would have either a Delay of NA (first incident) or Delay >50. The Start time would then be the start time of the first incident (either NA or >50) and the End time would be that of the last incident <=50 (see example with data below). I would also like the sum of X1 within the combined incidents. Hopefully the data below clarifies exactly what I am looking for.

Original Data:

ID          Incident    Start   End     X1   Delay
Person A    1           747     748     735  NA
Person A    2           868     882     384  120
Person A    3           998     999     354  116
Person A    4           1057    1059    382  58
Person A    5           1063    1064    138  4
Person A    6           1077    1078    138  13
Person A    7           1412    1413    384  334
Person B    1           739     740     387  NA
Person B    2           742     743     132  2
Person B    3           760     761     386  17
Person B    4           768     769     731  7
Person B    5           835     835     894  66
Person B    6           838     839     891  3
Person B    7           925     926     385  86

Desired Data:

ID          Iteration   Start   End     X1      Delay
Person A    1           747     748     735     NA
Person A    2           868     882     384     120
Person A    3           998     999     354     116
Person A    4           1057    1078    658     58
Person B    5           1412    1413    384     334
Person B    1           739     769     1636    NA
Person B    2           835     839     1785    66
Person B    3           925     926     385     86

I have tried multiple things, the issue is I just can't aggregate by ID because the same person might have two separate incidents.

Thanks! and let me know if you need any more information.

Aucun commentaire:

Enregistrer un commentaire