Reputation: 49
I want to aggregate my variables A1,.., A5 by creating a new variable A that is equal to A1,..,A5 whenever the corresponding r`k' is equal to 1. I have too many variables that I want to aggregate like this way and I was wondering maybe is there a way to write it more compactly than my code below. (I'm guessing that foreach can be used here but I'm not sure how)
gen A=.
gen B=.
forvalues k=1/5 {
replace A=A`k' if r`k'==1
replace B=B`k' if r`k'==1
}
Upvotes: 0
Views: 447
Reputation: 37288
This maps one loop into two:
foreach v in A B
gen `v' = .
forvalues k=1/5 {
replace `v' = `v'`k' if r`k'==1
}
}
But perhaps your data structure needs revisiting, so that instead of looping twice you could get something else more simply. So, if it makes sense, stacking A B
whatever into one variable would remove one loop.
Upvotes: 1