Search code examples
stataprefixlocal-variables

Looping over many variables with the same prefix in their name


I have many variables starting by the same prefix grado.

I would like to keep an observation when at least one of these variable equals a certain value, say 4. Elements of the variables grado*are byte.

I have created a local and looped over its elements to create a dummy taking value 1 when at least one of the grado*variables is 4. However, although this runs without error it does not change the value of my dummy to 1 when the condition is satisfied — so basically nothing happens.

See below the code I have used:

local A grado*
generate dummy = 0

foreach y of local A{
    replace dummy = 1 if `y' ==4
}

My input data looks like this:

col1 grado1 grado2
 3     6      4
 4     4      4
 2     4      8      
 4     7      2

I would like to obtain the following output:

col1 grado1 grado2 dummy
 3     6      4      1
 4     4      4      1
 2     4      8      1
 4     7      2      0

Solution

  • I am surprised at the claim that this runs without error, as your code is illegal. As an amplified example shows,

    clear 
    input grado1 grado2 
    0 4 
    1 1 
    end 
    
    local A grado*
    generate dummy = 0
    
    foreach y of local A { 
        display "`y'" 
        replace dummy = 1 if `y' == 4
    }
    

    your loop is a loop over a single item grado* -- as putting a wildcard into a local doesn't unpack the wildcard. So the pertinent part of the code becomes

    if grado* == 4 
    

    which produces an error message. I can only guess that you did something different.

    Notice that this works

    gen dummy = 0
    
    foreach y of varlist grado* { 
        display "`y'" 
        replace dummy = 1 if `y' == 4
    }
    

    as does this one-liner

    egen wanted = anymatch(grado*), value(4)