Home > Software engineering >  Making foreach go through all values of a variable return the current value
Making foreach go through all values of a variable return the current value

Time:12-17

I want to build an iteration using the Stata FAQ here. The second method seems fitting for my case. I have built the following code:

levelsof ID, local(levels)
foreach l of local levels {
    var var1 var2 if ID == `l', lags(1/4) vsquish
    vargranger
}

Idea: iterate over all IDs in ID, then do vargranger. However, it runs once, then outputs no observations. Which is not true, as I have 200 IDs in my search variable.

Second thing I want to add into my loop, a return / print function of the current ID used in ID.

The output should look like this, for each value of ID:

ID = XYZ

Sample:  2001 - 2019                            Number of obs     =         16
...

vargranger

   Granger causality Wald tests
   ------------------------------------------------------------------ 
  |          Equation           Excluded |   chi2     df Prob > chi2 |
  |-------------------------------------- ---------------------------|
  |         var1                    var2 |  11.617     4    0.020    |
  |         var1                     ALL |  11.617     4    0.020    |
  |-------------------------------------- ---------------------------|
  |         var2                    var1 |  6.2796     4    0.179    |
  |         var2                     ALL |  6.2796     4    0.179    |
   ------------------------------------------------------------------ 

CodePudding user response:

display of the current level is easy enough, say:

levelsof ID, local(levels)
foreach l of local levels {
    di "{title:`l'}" _n 
    count if !missing(var1, var2) & ID == `l'
    var var1 var2 if ID == `l', lags(1/4) vsquish
    vargranger
}

The report "no observations" is presumably coming from var and is not a reflection of how many identifiers you have. You should add checks like that above for (e.g.) how many observations you have to play with.

  • Related