Dear Statalist,

I have the following data. Each individual have done multiple angiographic examinations with each examinations possibly resulting in multiple treatments. Each observation is a treatment. Im trying to create a variable looping through each individual and identifying if a treated segment
gets treated again in the next examination. I have tried to lift up the information using a loop but its inneffective and requires modification of the variables .

Code:
foreach a in 1 2 3 4 {
by idnr : gen newvar`a' = segment_pci[_n+`a'] 
by idnr : gen date_of_angio`a' = date_of_angio[_n+`a'] 
}

replace newvar1=. if newvar1!=segment_pci
replace date_of_angio1=. if newvar1!=segment_pci

My question is, is there a forvalues loop that can run through each individual, identifying if each treated segment appears in a different examination
and create a new variable on the right segment as is shown in newvar and newvardate?

idnr angio_nr date of angio segment_pci newvar newvardate
54 1 18-Nov-11 8 1 28-Jan-12
54 1 18-Nov-11 7 1 28-Jan-12
54 1 18-Nov-11 6 1 28-Jan-12
54 2 28-Jan-12 8
70 1 26-Sep-10 2
70 1 26-Sep-10 12
70 1 26-Sep-10 6
81 1 26-aug-10 6
81 2 10-Apr-12
81 2 10-Apr-12
81 3 02-Aug-17
81 4 23-Nov-17 2 1 23-Dec-17
81 4 23-Nov-17 3 1 23-Dec-17
81 4 23-Nov-17 1 1 23-Dec-17
81 5 23-Dec-17 3
86 1 09-Sep-13
86 1 09-Sep-13 6
86 2 09-Oct-13 2
86 2 09-Oct-13 3
86 2 09-Oct-13 1
86 3 11-Dec-13 11 1 02-Jan-14
86 4 02-Jan-14 11
90 1 17-Jan-14
90 2 25-May-18 11

Sincerely,
Moman
and many thanks for a splendid forum!!!