If you want the correlation between a and b, what
c d e are doing is unnecessary information. A more
direct approach is
gen corrab = .
qui forval i = 1988(1)2003 {
forval j = 1/12
corr a b if year == `i' & month == `j'
replace corrab = r(rho) if year == `i' & month == `j'
}
}
In your example, each correlation is based on just 3 data points.
Perhaps you are obliged to do that, but I wouldn't want to.
Also, note Nick Winter's -egen, corr()- within -egenmore- on SSC.
Nick
[email protected]
Wang,Le
> I have a question on loop within loop. I have the following data set
>
> year month date a b c
> 88 1 1 .2 .5 .3
> . 1 2 .3 .6 .4
> . 1 3 .4 .7 .5
> . 2 1 .1 .2 .7
> . 2 2 .4 .5 .9
> . 2 3 .6 .7 1
> 89 1 1 .2 .5 .3
> . 1 2 .3 .6 .4
> . 1 3 .4 .7 .5
> . 2 1 .1 .2 .7
> . 2 2 .4 .5 .9
> . 2 3 .6 .7 1
>
> I could program the correlation by year as follows,
>
> g corrab = .
>
> forvalues i = 1988(1)2003{
> matrix accum R`i' = a b c if year == `i', nocons dev
> matrix R`i' = corr(R`i')
> replace corrab = R`i'[2,1] if year == `i' & corrab == .
> }
>
> However, now I want to calculate the correlation between a
> and b by year
> and month. What should I do?? I tried the following, but it
> doesnot work.
>
> forvalues i = 1988(1)2003 {
> local j = 1
> while `j' < 13{
> matrix accum R`i'`j' = a b c d e if year == `i' &
> month == `j',
> nocons dev
> matrix R`i'`j' = corr(R`i'`j')
> replace corrab = R`i'`j'[1,1] if year == `i' &
> month == `j' &
> corrab == .
> local `j' = `j' + 1
> }
> }
>
*
* For searches and help try:
* http://www.stata.com/support/faqs/res/findit.html
* http://www.stata.com/support/statalist/faq
* http://www.ats.ucla.edu/stat/stata/