繁体   English   中英

Stata foreach 循环从变量名列表中生成新变量

[英]Stata foreach loop to generate new variables from a list of variable names

我正在寻找创建一个循环,该循环创建虚拟变量并从变量名列表中命名它们,然后在所有变量名都被迭代一次后停止。

我的尝试:


gen c = 0
foreach x of varlist stchpr01-stchpr11{
        foreach i in teacher_late teacher_absent teacher_skip teacher_bully teacher_harass_teachers teacher_harass_pupils teacher_language teacher_drugs teacher_alcohol teacher_health teacher_conflict{
            while c < 11{
                gen  `i' = 0
                replace `i' = 1 if `x' == 2 | `x' == 3
                replace `i' = 0 if `x' == 1
                replace `i' = . if missing(`x')
                replace c = c+1
            }
        }
}

我感觉到你在

  • Stata 意义上的本地宏和变量(虽然c机器是合法的,但本地宏更适合用作计数器,除了你根本不需要)

  • 在您尝试generate已经存在的变量时generatereplace

  • 并行循环,不是嵌套循环

(对我来说)有点不清楚的正是你想要做的。

我认为这就是你想要的。

  • 您有 11 个现有变量。

  • 您需要 11 个对应的新变量,如果对应的现有变量为 2 或 3,则每个新变量为指示符 1,如果为 1,则为 0,否则为缺失。

如果是这样,这是一个代码草图。 注意:这只是一个循环。

local newvars teacher_late teacher_absent teacher_skip teacher_bully teacher_harass_teachers teacher_harass_pupils teacher_language teacher_drugs teacher_alcohol teacher_health teacher_conflict
            
foreach x of varlist stchpr01-stchpr11 {
    gettoken new newvars : newvars 
    gen `new' = cond(`x' == 2 | `x' == 3, 1, cond(`x' == 1, 0, .)) 
} 

另见https://journals.sagepub.com/doi/pdf/10.1177/1536867X211063415

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM