具有两个索引的forvalues

时间:2017-06-13 00:26:41

标签: loops for-loop stata

我想在Stata中循环两个不同的值,一个公司标识符和一个年变量,并为每个组合执行回归。 代码看起来应该是这样的。

    gen unexplained = .
    forvalues j = 1/16 {
       forvalues t = 2010/2016 {
       quietly reg y x if firm_id == `j' & year == `t', nocon
       predict error, residuals
       quietly replace unexplained = error if firm_id == `j' & year == `t'
       drop error
       }
    }

因此应该有16 x 6 = 96个单独的回归。

不幸的是,我得到了一个

no observations 
r(2000) 

错误消息。我知道我错误地编入索引。

1 个答案:

答案 0 :(得分:1)

一个答案是检查每个回归可用的观察数量,并且仅当您有足够的回归值时才能检查regress。选择一个小编号就可以了。

gen unexplained = .

quietly forvalues j = 1/16 {
    forvalues t = 2010/2016 {
        count if !missing(y, x) & firm_id == `j' & year == `t'
        if r(N) >= 7 { 
            reg y x if firm_id == `j' & year == `t', nocon
            predict error, residuals
            replace unexplained = error if firm_id == `j' & year == `t'
            drop error
        }
    }
}

包含计数的变量也可能有用:

bysort firm_id year: egen available_n = total(!missing(y, x))