So i have different visitors, each having come more than once.
From the visit dates i got the visit gaps for each patient.
I want to assign episodes for each visits of each patient depending on their gaps. For Gap=0
(ie 1st visit of any new patient), Episode=1
. If Gap>20
, Episode=previous episode+1
, if Gap<=20
, Episode=previous Episode
. And the whole thing starts again for new patient. I want to do this without using loop in R , preferably in dplyr.
Data :
Df <- data.frame(Visitors = c("V1","V1","V1","V1","V1","V1","V1","V2","V2","V2","V2","V2","V2","V3"),
Gap=c(0,6,18,35,43,9,11,0,3,67,98,12,2,0))
This is the expected Table :
Visitors Gap Episodes
V1 0 1
V1 6 1
V1 18 1
V1 35 2
V1 43 3
V1 9 3
V1 11 3
V2 0 1
V2 3 1
V2 67 2
V2 98 3
V2 12 3
V2 2 3
V3 0 1