Code:
* Example generated by -dataex-. For more info, type help dataex clear input float Diagnosis1 str4(Diagnosis4 Diagnosis5) 3 "T345" "T345" 3 "T88" "T77" 34 "T76" "T88" 3 "T76" "A76" 3 "A89" "A89" end
Hi there I was playing around with Stata at home trying to test the command foreach.
Aim: To generate a Diagnosis4 and Diagnosis5 separate columns into numerical values with labels attached to them.
Command used:
foreach pathology of Diagnosis4 Diagnosis5 {
generate 'pathology' diagx = 0
replace diagx == 1 if Diagnosis4 == T345 | T88
replace diagx == 2 if Diagnosis4 == T77
label define 1 "stroke" 2 "diabetes"
}
My explanation:
foreach - loop used as I am using string values
pathology - name of the macro
Diagnosis4 Diagnosis5 - the variable columns I would like Stata to run the command
generate 'pathology'
diagx = new column I would like to create
replace - replacing the 0 into the the values I want then labelling accordinly
My question:
1. How can I create a new column with a custom name ie Diagx4 ; Diagx5 and each time stata cycles through the loop (in bold) each time replacing the command
2. Do I have to write the generate commands myself ie gen Diagx4 = 0 ; gen Diagx5 = 0 and thus copy and past the foreach command after each generate command?
3. If it's a No to 2, how can I include this in the loop ?
Comment