Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Creating a loop for time regression

    Hello,

    I am investigating trends in R2 over time by regressing it over time. Because I need to do it for 16 variables and for 12 industries I was trying to improve the following code so that it generates 16 regression outputs for each variable. I tried to do it by creating a varlist and using loop foreach but I got lost.

    I was wondering if somebody knows how to do it quickly and easily?

    Code:
    gen R2ibpr =.
    forvalues i = 1962(1)2017 {
    display "`i'"
    reg prc ibpr if  pyear==`i'
    replace R2ibpr = e(r2_a) if pyear == `i'
    }
    keep pyear R2ibpr
    
    duplicates drop
    sort pyear
    
    gen time = pyear-1961
    reg R2ibpr time
    Code:
          Source |       SS           df       MS      Number of obs   =        56
    -------------+----------------------------------   F(1, 54)        =      1.80
           Model |  .053632868         1  .053632868   Prob > F        =    0.1859
        Residual |  1.61346458        54  .029878974   R-squared       =    0.0322
    -------------+----------------------------------   Adj R-squared   =    0.0142
           Total |  1.66709745        55  .030310863   Root MSE        =    .17286
    
    ------------------------------------------------------------------------------
          R2ibpr |      Coef.   Std. Err.      t    P>|t|     [95% Conf. Interval]
    -------------+----------------------------------------------------------------
            time |   .0019147   .0014291     1.34   0.186    -.0009505    .0047798
           _cons |   .3718075   .0468233     7.94   0.000     .2779325    .4656825
    ------------------------------------------------------------------------------
    Thank you for taking your time to help me,

    Jakub

  • #2
    Hi,
    you need to nest several loops for: year, variable and industry.

    Code:
    local variables "va1 var2 ... var16"
    forvalues i = 1962(1)2017 {
        foreach var of local variables {
            if `i'==1962 gen R2`var' = .
            levelsof industry if pyear==`i' & !mi(prc, `var'), local(industries)
            foreach ind of local industries {
                reg prc `var' if pyear==`i' & industry==`ind'
                replace R2`var' = e(r2_a) if pyear == `i' & industry==`ind'
            }
        }
    }
    I haven't test the code, hope it works and does what you need.

    Raffaele

    Comment

    Working...
    X