【问题标题】:Invalid syntax (r198) for foreach loopsforeach 循环的无效语法 (r198)
【发布时间】:2021-05-11 17:51:15
【问题描述】:

我在 Stata 中重新编码我的序数变量,以使值变得更直观,即等级越高,我的变量名称打算测量的程度越高。

例如,回答“您对自己的国家有多近?”这个问题的答案。编码:1 - 非常接近 2 - 接近 3 - 不太接近 4 - 根本不接近

我想以这种方式重新编码我的新变量“close_country”:4 - 非常接近,3 - 接近,2 - 不太接近,1 - 根本不接近

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

【问题讨论】:

    标签: foreach stata


    【解决方案1】:

    您的代码似乎减少到

    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'
    }
    

    --甚至

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

    错误在

    foreach `close' in `closes'
    

    你的意思

    foreach close in `closes'
    

    【讨论】:

    • 谢谢!我有 59 个变量,所以我在 Excel 中使用了连接。非常感谢您指出 foreach 中的错误。 :D
    猜你喜欢
    • 2019-03-16
    • 2011-05-26
    • 1970-01-01
    • 1970-01-01
    • 2017-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多