Search code examples
stata

Create variables by multiplying variables that have the same name suffix


I have a Stata dataset that looks like this:

stock8201 stock8202 stock8203 immigrantshare8201 immigrantshare8202 immigrantshare8203
123 24 21 0.0004696 0.0001165 0.0016181
123 24 21 0.0004696 0.0001165 0.0016181
123243 24 21 0.0004696 0.0001165 0.0016181

And I want a command that would create for me three variables that would multiply the first one stock8201 by immigrantshare8201 and do the same for the other ones. The table I want at the end would look something like this:

Predi8201 Predi8202 Predi8203
0.0577608 0.002796 0.0339801
0.0577608 0.002796 0.0339801
57.8749128 0.002796 0.0339801

which is for instance: Predi8201 which is equal to stock8201*immigrantshare8201


Solution

  • forval j = 1/3 { 
        gen Predi820`j' = stock820`j' * immigrantshare820`j' 
    } 
    

    For a larger set of variables, you might want something like

    foreach v of var stock* { 
         local suffix : subinstr local v "stock" "" 
         gen Predi`suffix' = `v' * immigrantshare`suffix' 
    } 
    

    Your question hints that you are holding data for different months (January 1982, February 1982, ...) in a wide layout. In Stata most things are easier in a long layout, which usually calls for reshape long.