Search code examples
loopsstatanested-loopsstata-macros

Brace required error in nested loop


I'm working on my first loop with a nested loop in Stata, but can't get the code to run.

Here is what I have:

*identify anti policies of contiguous states
forvalues yr = 1983/1993 {
foreach state in Alabama Alaska Arizona Arkansas California Colorado 
Connecticut Delaware Florida Georgia Hawaii 
Idaho Illinois Indiana Iowa Kansas Kentucky Louisiana Maine Maryland 
Massachusetts Michigan Minnesota Mississippi 
Missouri Montana Nebraska Nevada NewHampshire NewJersey NewMexico NewYork 
NorthCarolina NorthDakota Ohio 
Oklahoma Oregon Pennsylvania RhodeIsland SouthCarolina SouthDakota Tennessee 
Texas Utah Vermont Virginia 
Washington WestVirginia Wisconsin Wyoming {
 gen 'st'_anti_'yr'=.
 replace 'st'_anti_'yr'=1 if 'st'_c==1 & anti["st"_"yr"]==1 
 replace 'st'_anti_'yr'=0 if 'st'_c==0 | anti["st"_"yr"]==0
}
}

When I run the code, I get the error:

r(100) or r(100) { required 

This error shows up no matter how I modify the code (adding or removing the ' or ", etc.).


Solution

  • You need to add /// at the end of each line so Stata can treat all states as one continuous line. It is also a good practice to save all the states in a local macro and then use this in the loop.

    For example:

    local states Alabama Alaska Arizona Arkansas California Colorado  Connecticut ///
    Delaware Florida Georgia Hawaii Idaho Illinois Indiana Iowa Kansas Kentucky ///
    Louisiana Maine Maryland Massachusetts Michigan Minnesota Mississippi ///
    Missouri Montana Nebraska Nevada NewHampshire NewJersey NewMexico NewYork ///
    NorthCarolina NorthDakota Ohio Oklahoma Oregon Pennsylvania RhodeIsland ///
    SouthCarolina SouthDakota Tennessee Texas Utah Vermont Virginia Washington ///
    WestVirginia Wisconsin Wyoming
    
    forvalues yr = 1983 / 1993 {
        foreach state of local states {
            display "`yr' `state'"
        }
    }
    

    In addition, in your example you seem to be mis-specifying the local macro state and forget to use quotes for the local macro yr:

    forvalues yr = 1983 / 1993 {
        foreach state of local states {
            generate `state'_anti_`yr'=.
            replace `state'_anti_`yr'=1 if `state'_c==1 & anti[`state'_`yr']==1 
            replace `state'_anti_`yr'=0 if `state'_c==0 | anti[`state'_`yr']==0
        }
    }