Search code examples
stata

select minimum value by ID, over range of visits


I'm trying to extract a variable for the lowest value over a range of visits, in this case:

I want the lowest value over first 3 days of admission (admission day 1 or 2 or 3) , by VisitID. any suggestions?

visitID    value    day of admission
1          941       1
1          948       2
1          935       4

2           83       1
2           84       2
2           50       4
2           79       5

and I would want:

visitID  value   visit   minvalue

1        941      1       941
1        948      2       941
1        935      4       941

2        83       1        83
2        84       2        83
2        50       4        83
2        79       5        83

Solution

  • It would have been helpful if you had presented your data in an easily usable form. But here's an approach that should point you in a useful direction.

    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input byte visitid int value byte day
    1 941 1
    1 948 2
    1 935 4
    2  83 1
    2  84 2
    2  50 4
    2  79 5
    end
    bysort visitid (day) : egen minvalue = min(cond(day<=3,value,.))
    

    Which results in

    . list, sepby(visitid)
    
         +----------------------------------+
         | visitid   value   day   minvalue |
         |----------------------------------|
      1. |       1     941     1        941 |
      2. |       1     948     2        941 |
      3. |       1     935     4        941 |
         |----------------------------------|
      4. |       2      83     1         83 |
      5. |       2      84     2         83 |
      6. |       2      50     4         83 |
      7. |       2      79     5         83 |
         +----------------------------------+