This is a technique that uses the lag function to hold needed values rather than a temporary variable. Much more compact in cases like this.
data have;
input Patient_id Regimen_ID Start_date :$2. Stop_date :$2.;
put (_all_) (=);
datalines;
1 1 A0 A1
1 1 B0 B1
1 1 C0 C1
1 2 A0 A1
1 3 A0 A1
1 3 B0 B1
run;
data want;
set have;
by patient_id regimen_id;
if first.regimen_id or last.regimen_id;
if first.regimen_id ^=last.regimen_id then start_date=lag(start_date);
if last.regimen_id;
run;
Notes:
I changed your regimen_id=2 to a 3, and added a single-record regimen_id=2 in the middle, to demonstrate treatment of single-record date ranges.
The first subsetting if (if first.regimen_id or last.regimen_id) tells SAS to throw away all records except the first and last for each group.
The "if first.regimen_id^=last.regimen_id ..." statement. If the regimen_id has only a single record, then no updating is needed. But if there are separate first. and last. records, then the single-member lag queue is updated twice for that regimen_id. Which in turn means that the result of the lag at the end of the group is the value that was put into the lag queue at the beginning of the group. Of course in this case the lag "queue" is a queue of size one.
The "if last.regimen_id" statement keeps one record per group -- the last record.
By the way, the single statement
if first.regimen_id^=last.regimen_id then start_date=lag(start_date);
is NOT EQUIVALENT to the pair of statements
if first.regimen_id>last.regimen_id then start_date=lag(start_date);
if first.regimen_id<last.regimen_id then start_date=lag(start_date);
because the single statement maintains only one queue of start_date values, alternating between values of the first. and last. records. In contrast, the two statements maintain two separate queues, one with the sequence of first. records, and the other with the sequence of last. records.
... View more