简体   繁体   English

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

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

I am looking to create a loop which creates dummy variables and names them from a list of variable names, and then stops once all variable names have been iterated over once.我正在寻找创建一个循环,该循环创建虚拟变量并从变量名列表中命名它们,然后在所有变量名都被迭代一次后停止。

My Attempt:我的尝试:


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

I sense that you are getting confused between我感觉到你在

  • local macros and variables in Stata's sense (although the c machinery is legal, local macros are better for use as counters, except that you don't need one at all) Stata 意义上的本地宏和变量(虽然c机器是合法的,但本地宏更适合用作计数器,除了你根本不需要)

  • generate and replace as you're trying to generate variables that already exist在您尝试generate已经存在的变量时generatereplace

  • loops in parallel, which are not nested loops并行循环,不是嵌套循环

What is a little unclear (to me) is exactly what you want to do. (对我来说)有点不清楚的正是你想要做的。

I take it this is what you want.我认为这就是你想要的。

  • You have 11 existing variables.您有 11 个现有变量。

  • You want 11 corresponding new variables, each of which is to be an indicator 1 if the corresponding existing variable is 2 or 3, 0 if it is 1, and missing otherwise.您需要 11 个对应的新变量,如果对应的现有变量为 2 或 3,则每个新变量为指示符 1,如果为 1,则为 0,否则为缺失。

If so, this is a code sketch.如果是这样,这是一个代码草图。 NB: it's just one loop.注意:这只是一个循环。

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, .)) 
} 

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

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

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