I have a dataframe that looks like this (but with 1000s of rows):
| Person_ID | Visit_ID | Time_Diff |
|---|---|---|
| 1 | 1 | NA |
| 2 | 2 | NA |
| 3 | 3 | NA |
| 3 | 4 | 1444 |
| 4 | 5 | NA |
| 4 | 6 | 0 |
| 4 | 7 | 0 |
| 4 | 8 | 180 |
| 5 | 9 | NA |
| 6 | 10 | NA |
| 7 | 11 | NA |
| 7 | 12 | 19 |
| 8 | 13 | NA |
| 8 | 14 | 25 |
| 9 | 15 | NA |
What you see from this is that:
- The same person_ID can be in multiple rows
- The Visit_ID always increments by 1
- The Time Diff is sometimes NA, sometimes negative, sometimes positive
What I want to do is to:
- Create a new Visit_ID (Let's call it New_Visit_ID)
- Start that ID from 1 on the first row and then increment for each row the Person_ID changes OR the Time_Diff is >24 (i.e. not NA or <=24)
What this means is that the same Person_ID with a time diff of <=24 should have the same New_Visit_ID, i.e. some kind of conditional increment.
Hope this is clear!
The desired output should be:
| Person_ID | Visit_ID | Time_Diff | New_Visit_ID |
|---|---|---|---|
| 1 | 1 | NA | 1 |
| 2 | 2 | NA | 2 |
| 3 | 3 | NA | 3 |
| 3 | 4 | 1444 | 4 |
| 4 | 5 | NA | 5 |
| 4 | 6 | 0 | 5 |
| 4 | 7 | 0 | 5 |
| 4 | 8 | 180 | 6 |
| 5 | 9 | NA | 7 |
| 6 | 10 | NA | 8 |
| 7 | 11 | NA | 9 |
| 7 | 12 | 19 | 9 |
| 8 | 13 | NA | 10 |
| 8 | 14 | 25 | 11 |
| 9 | 15 | NA | 12 |