I want to use a foreach
loop to execute commands over two lists of variables at once. My question can best be explained with an example:
Example: In my loop, I want refer to variables both for a given year and for the year two years prior. For example, in the first iteration of my loop, I'd hope to refer to variables for a given year (2000), and for the year two years prior to that year (1998). In the next iteration, I'd like to refer to variables for the next given year (2002) and for the year two years prior (2000). Here is some sample code:
foreach y in 2000 2002 2004 2006 {
gen employment`y' = 0
replace employment`y' = . if work_1998==. | work_`y'==.
replace employment`y' = 1 if work_1998==1 & work_`y'==1
}
This code works great for the year 2000, where I need to call in variables for years 2000 and the year 1998 (two years prior to 2000). But for 2002, 2004, etc., I need to replace the 1998
in the above code with something that basically calls in the "year two years prior" automatically, instead of just using the numbers "1998". I'm not sure how to do this. Any advice is appreciated!
question from:
https://stackoverflow.com/questions/65877530/how-to-use-foreach-loop-over-two-variables-at-once 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…