Home > Mobile >  Stata foreach loop to generate new variables from a list of variable names
Stata foreach loop to generate new variables from a list of variable names

Time:05-18

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

CodePudding user response:

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)

  • generate and replace as you're trying to generate variables that already exist

  • 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.

  • 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.

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

  • Related