I’m having a rather silly problem with a simple forval loop, such that the last cycle of the loop seems to be populating all previous local macros created therein. I am simply trying to record a series of r-squared values in a matrix over subsets of observations defined by a decile variable (here called var3). My code is:
r2 [10,2]
where, as you can see, all r-squared values have been replaced with the most recent value generated – even though if I insert a command line into the loop to display its output in media res (di rsquare`i' inserted just below local rsquare`i' e(r2_o)), I obtain a series of distinct results (but still the same homogenous matrix at the end).
If I run a similar forval loop without the regression and r-square extraction, there’s no problem:
r2 [10,2]
Many thanks.
Version: Stata 13.1 (up to date)
forval i = 1/10 {The resulting matrix is something like:
qui xtreg var1 var2 if var3==`i'
local rsquare`i' e(r2_o)
}
matrix define r2wide = (1,2,3,4,5,6,7,8,9,10\`rsquare1',`rsquare2',`rsqua re3',`rsquare4',`rsquare5',`rsquare6',`rsquare7',` rsquare8',`rsquare9',`rsquare10')
matrix r2 = r2wide'
matrix list r2
r2 [10,2]
| r1 | r2 | |
| c1 | 1 | 0.245521 |
| c2 | 2 | 0.245521 |
| c3 | 3 | 0.245521 |
| c4 | 4 | 0.245521 |
| c5 | 5 | 0.245521 |
| c6 | 6 | 0.245521 |
| c7 | 7 | 0.245521 |
| c8 | 8 | 0.245521 |
| c9 | 9 | 0.245521 |
| c10 | 10 | 0.245521 |
If I run a similar forval loop without the regression and r-square extraction, there’s no problem:
forval i = 1/10 {yields:
local rsquare`i' `i'
}
matrix define r2wide = (1,2,3,4,5,6,7,8,9,10 \ `rsquare1',`rsquare2',`rsquare3',`rsquare4',`rsqua re5',`rsquare6',`rsquare7',` rsquare8',`r2QtauS9',`rsquare10')
matrix r2 = r2wide'
matrix list r2
r2 [10,2]
| r1 | r2 | |
| c1 | 1 | 1 |
| c2 | 2 | 2 |
| c3 | 3 | 3 |
| c4 | 4 | 4 |
| c5 | 5 | 5 |
| c6 | 6 | 6 |
| c7 | 7 | 7 |
| c8 | 8 | 8 |
| c9 | 9 | 9 |
| c10 | 10 | 10 |
Version: Stata 13.1 (up to date)

Comment