How to generate a group summary categorical variable for survival analysis in Stata? I have registry data for which I have data for individuals for each hospital attendance over a 10 year period.  I wish to determine the effect of chronic antibiotic use upon acquisition of specific infections (outcome).  However, often the choice of antibiotic may differ over time and so I want to be able to summarise individuals' antibiotic use so that eventually I can group individuals with similar exposures.
In order to do this I have generated an indicator variable that records each hospital visit as first, second visit, etc.  However I cannot work out how I may then use this to summarise individuals' exposure.  Any ideas?
 A: Suppose that in your original data set, you have patient ID, visit time, and drug prescribed (empty if nothing was prescribed), assuming that drug values are clean, standardized, and can be nicely matched.
    * eliminate visits with no antibiotics
    drop if missing(drug)
    * count how many times each drug was present
    bysort patient (drug visit): generate int times_prescribed = _N
    * create long data
    bysort patient drug (visit) : drop if _n > 1
    bysort patient (drug) : generate int drug_no = _n
    rename visit first_prescribed
    compress
    * create wide data
    reshape wide drug first_prescribed times_prescribed , i(patient) j(drug_no)

This should produce a data set with one record per patient. Depending on the particular analysis goals, you may find it easier to work with wide or long data. The variable(s) times_prescribed1 (the first antibiotic ever prescribed), times_prescribed2 (second antibiotic, if ever switched to another one), etc. should works as proxies for the exposure. You can also add the total number of times any of the drugs were prescribed:
    bysort patient (drug visit): generate int total_prescriptions = _N

after drop if  missing(drug), and/or the total number of different drugs ever prescribed:
    bysort patient (drug): generate int number_of_drugs = _N

after drop if _n>1. You'd need to carry them as constant in reshape; if you don't specify them anywhere, that's what should happen to them automatically, I believe.
