Hello, everyone. I started learning Stata since last year. I have tried to search by google and Statalist to solve it out but in vain. So, I hope to get some help or hint here. My dataset consists of data for each id's spending in hospitals. Now, I would like to merge records of each id in re-admitted to same hospital within 2 days. Taking idg=262 as sample of observations, I am able to sum the total batches of spending to 4. My next step is to group these by each batch using identifier before further sum of spending by identifier group. My code for generating the identifier is as below but only reach at 2. I also tried to use if else but seems not working as well.
Hope to get some help or idea here. Some of the data and code are as below:
Data:

Hope to get some help or idea here. Some of the data and code are as below:
Data:
Code:
sort idg in_date
gen identifier = .
bys idg : replace identifier = 1 if _n == 1
forval i = 2/`=_N' {
by idg: replace identifier = identifier[_n-1] + 1 if (hosp_idg == hosp_idg[_n-1] & lessthan2days != lessthan2days[`i'-1])
by idg: replace identifier = identifier[_n-1] if (hosp_idg == hosp_idg[_n-1] & lessthan2days == lessthan2days[`i'-1])
}

Comment