Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Create batch identifier by forval or if else?

    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:

    Click image for larger version

Name:	Capturestata.JPG
Views:	1
Size:	108.0 KB
ID:	1753591



    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])
    }

  • #2
    It looks like you want hosp_idg to also be a delineater of what constitutes each batch, so I think you need 5 batches. Batch 1 is 467, batch 2 is 468, batch 3 is 469-473, batch 4 is 474, and batch 5 is 475-476. As long as the dates are numbers (not strings), I would do this:

    Code:
    bysort idg (in_date): generate identifier = 1 if _n == 1
    bysort idg (in_date): replace identifier = identifier[_n-1] + ((hosp_idg != hosp_idg[_n-1]) | ((in_date - out_date[_n-1]) > 2)) if _n > 1

    Comment


    • #3

      Originally posted by Brian Bradfield View Post
      It looks like you want hosp_idg to also be a delineater of what constitutes each batch, so I think you need 5 batches. Batch 1 is 467, batch 2 is 468, batch 3 is 469-473, batch 4 is 474, and batch 5 is 475-476. As long as the dates are numbers (not strings), I would do this:

      Code:
      bysort idg (in_date): generate identifier = 1 if _n == 1
      bysort idg (in_date): replace identifier = identifier[_n-1] + ((hosp_idg != hosp_idg[_n-1]) | ((in_date - out_date[_n-1]) > 2)) if _n > 1
      Thanks Brian. It works well. And you did point out hosp_idg difference that I missed too.

      Comment

      Working...
      X