I've done something very similar in the past only it was in a database
program. I sorted the data on patient in ascending order, but within
patient in descending date order so one worked toward the past as Nick
has suggested. What I did, however, was to write my results to a new
file as I scanned the old one. Stata would allow you to do this with
postfile where you would duplicate the information of the variables in
your original data and also add the derived variables for switch,
interval, etc., posted to the postfile.
In greater detail: Original file (A), postfile (B)
[commands to create a postfile]
forvalues i=1/`c(N)' {
[commands to read in A[`i'] variables]
local this_scrssn scrssn[`i'] //initialize scrssn
local j = `i'
while scrssn[`j']== `this_scrssn' & `j' <= `c(N)' { // while same individual
local ++j
[commands to read in A[`j'] variables]
[logic to compare `i'th prescription to `j'th prescription and
decide if add or switch]
[post to B]
continue //break out of while once we are sure about the index prescription
}
}
and so on. I have left it to you to fill in the [black boxes] (I'm
put in mind of this famous cartoon:
http://www.people.virginia.edu/~del6n/miracle.jpg ). I'd be
interested to see how this comes out.
DCE
*
* For searches and help try:
* http://www.stata.com/support/faqs/res/findit.html
* http://www.stata.com/support/statalist/faq
* http://www.ats.ucla.edu/stat/stata/