I have a healthcare dataset that codes a principal diagnosis using a variable 'I10_DX1' and secondary diagnoses as 'I10_DX2' to 'I10_DX40' such that a patient has the possibility of having 39 separate secondary diagnoses coded upon an encounter. These are string variables using ICD-9-CM or ICD-10-CM classification systems.

I am attempting to code comorbidities based on these 39 potential secondary diagnoses to capture all patients who may have this comorbidity captured during their hospital encounters. With this, I am attempting to use "foreach loops" to minimize the amount of code necessary to generate these variables. I have a working code that indicates I have generated a variable, but I am experiencing challenges generating a table or using the 'tab' command to view the number of patients with these comorbidities.

As an example, I am looking to generate "previous myocardial infarction" as a comorbidity, based on the ICD-10-CM classification system, using the code below.

Code:
foreach x of varlist I10_DX2-I10_DX40 { 2. gen `x'_test_prevMI = 0 3. replace `x'_test_prevMI = 1 if `x'== "I252" 4. }
Stata indicates that the variable is generated without an error message. However, when I attempt to generate descriptive statistics using the tab function within the foreach loop, I receive 39 table outputs for I10_DX2_test_prevMI to I10_DX40_test_prevMI instead of just one table for `x'_test_prevMI.

Code:
foreach x of varlist I10_DX2-I10_DX40 { 2. tab `x'_test_prevMI 3. } Does anyone have any insight as to how I could revise my code such that I receive one descriptive statistics table for the variable "`x'_test_prevMI"? Any advice and/or guidance is welcome and greatly appreciated!