Nested Loops

Reminder

Please use all code samples responsibly - these are samples and likely require adjustments to work correctly for your specific needs. Read through the documentation and comments to understand any caveats or limitations of the code and/or data and follow-up with the code author or Code Library admins if you have questions on how to adapt the sample to your specific use case.

Purpose: This code loops through a wide data set of the number of arrests per person and calculates the number of theft arrests per person, as well as the number of theft arrests per person per year (nested loop).

Note

This code comes from the stata-user group training series for more info see here.*

Data: The code sample uses a fake arrest data set that was used in the Intro to Stata training series, but is applicable to any data that you want to get person level sums, or annual person level sums.

#Want to generate a variable that's the number of theft arrests per person 
#could write out arr_theft_tot=arr_theft1 + arr_theft2 +...+arr_theft39 
#or use a loop to do this all more easily in one step
tab arr_theft4, m
tab arr_theft4, m nolabel   

#If any of the values are missing the sum will be 
#missing, so this command sets the original variables to 0 if missing*
forvalues i=1(1)39 {
    replace arr_theft`i' = 0 if arr_theft`i` == .
}

gen arr_theft=0         /*Can only generate once so do it before the loop*/     

forvalues i=1(1)39 {
    replace arr_theft=arr_theft + arr_theft`i`
    }
    
list id arr_theft arr_theft1 arr_theft2 arr_theft3 arr_theft4  in 1/10                                      

#Want to generate a variable that's the number of arrests per year per person
#Can loop within loops
forvalues j=2012(1)2014 {
    gen arr_`j`=0
    forvalues i=1(1)39  {
        replace arr_`j`=arr_`j`+1 if arr_y`i`==`j`
        }
    }
list id arr_2012 arr_y1 arr_y2 arr_y3 arr_y4  in 1/10