mardi 7 juillet 2020

How can I sum consecutive rows if a condition is satisfied in R?

I have a dataframe,

     Date_Time ID Activity ID2 Duration
23 2014-12-21 13:07:00    NI       A      OF    69180 secs
36 2014-12-22 09:22:00    TY       A      JU       60 secs
37 2014-12-22 09:23:00    TY       B      JU      420 secs
38 2014-12-22 09:30:00    TY       C      JU      900 secs
45 2014-12-22 10:50:00    TY       B      KJ      300 secs
63 2014-12-22 14:40:00    TY       A      KJ      300 secs

I want to create a conditional statement that will sum consecutive rows of the Duration column if

The Date_Time in the previous row - Date_Time + Duration on that row is < 60

2014-12-22 09:23:00 - (2014-12-22 09:22:00 + 60) < 60

and if both ID and ID 2 are the same in those consecutive rows.

The result should look like this:

 Date_Time ID Activity ID2 Duration Duration_Sum
23 2014-12-21 13:07:00    NI       A      OF    69180 secs    69180 secs
36 2014-12-22 09:22:00    TY       A      JU       60 secs        0 secs
37 2014-12-22 09:23:00    TY       B      JU      420 secs      480 secs
38 2014-12-22 09:30:00    TY       C      JU      900 secs     1380 secs
45 2014-12-22 10:50:00    TY       B      KJ      300 secs        0 secs
63 2014-12-22 14:40:00    TY       A      KJ      300 secs        0 secs

Hope you can give me some help. This is my frist day using R... So if you could also explain your steps it would be great!

Thank you!

Aucun commentaire:

Enregistrer un commentaire