Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
684 views
in Technique[技术] by (71.8m points)

stata - How to use foreach loop over two variables at once?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It's still one loop:

foreach y in 2000 2002 2004 2006 {
    local Y = `y' - 2 
    gen employment`y' = 0
    replace employment`y' = . if work_`Y' ==. | work_`y'==.
    replace employment`y' = 1 if work_`Y' ==1 & work_`y'==1
}

That said, you would probably be much better off with applying reshape long so that data for different years are held in different observations, not different variables.

Your calculation of the new variable could be reduced to

gen employment`y' = work_`Y' ==1 & work_`y'==1 if !missing(work_`y', work_`Y') 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...