Search code examples
foreachstata

Invalid syntax (r198) for foreach loops


I am recoding my ordinal variables in Stata in order for the values to become more intuitive i.e., the higher rank, the higher degree of what my variable name intends to measure.

For instance, answers to the question "How close you feel to your country?" are coded: 1 - Very close 2 - Close 3 - Not very close 4 - Not close at all

I want to recode my new variable "close_country" this way: 4 - Very close, 3 - Close, 2 - Not very close, 1 - Not close at all

rename v1 close_city
rename v2 close_province
rename v3 close_country
rename v4 close_continent
rename v5 close_ethnic
gen close_city_1=.
gen close_province_1=.
gen close_country_1=.
gen close_continent_1=.
gen close_ethnic_1=.

local closes "city province country continent ethnic"
foreach `close' in `closes' {
    replace close_`close'_1 = 4 if close_`close'==1
    replace close_`close'_1 = 3 if close_`close'==2
    replace close_`close'_1 = 2 if close_`close'==3
    replace close_`close'_1 = 1 if close_`close'==4
    }
replace close_city_1 = 4 if close_city==1 // this works fine
replace close_city_1 = 3 if close_city==2 // this works fine

Solution

  • Your code seems to reduce to

    rename (v1-v5) (close_city close_province close_country close_continent close_ethnic) 
    
    local closes "city province country continent ethnic"
    foreach v of local closes { 
        gen close_`v'_1 = 5 - close_`v'
    }
    

    -- or even

    foreach v in city province country continent ethnic { 
        gen close_`v'_1 = 5 - close_`v'
    }
    

    The error is in

    foreach `close' in `closes'
    

    where you meant

    foreach close in `closes'