= medication_code[_n - 1] if _n > 1 or something analogous that will flag prescription changes within each patient. You can then home-in on the cases of interest among flagged patients with something like replace medication_change = 0 if !inlist(medication_code, "A", "B", "C") by...