Home > database >  How can I use a loop to create lag variables?
How can I use a loop to create lag variables?

Time:09-25

* Example generated by -dataex-. To install: ssc install dataex
clear
input int(date date2)
18257 16112
18206 16208
17996 16476
18197 17355
18170 17204
end
format %d date
format %d date2

I'm trying to create a loop in Stata that generates four variables (lags at 0 months, 3 months, 12 months, and 18 months). I tried this (below) and I get an error: invalid syntax

foreach x inlist (0,3,12,18) & foreach y inlist (0,90,360,540){
    gen var`x' = (date > date2   `y')
    
}

Here is a way for me to successfully create these variables without the loop. It would be much nicer if it could be simplified with a loop.

gen var0=(date>date2)
gen var3=(date>date2 90)
gen var12=(date>date2 360)
gen var18=(date>date2 540)

CodePudding user response:

Good news: you need just one loop over 4 possibilities, as 0 3 12 18 and 0 90 360 540 are paired.

foreach x in 0 3 12 18 { 
    gen var`x' = date > (date2   30 * `x') 
    
}

foreach requires either in or of following the macro name, so your code fails at that point. There is also no construct foreach ... & foreach ....: perhaps you are using syntax from elsewhere or just guessing there.

  • Related