Announcement

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

  • Retrieve count of increment in foreach-loop

    Dear community,

    I would like to ask for your help concerning the following issue.

    The scenario is as follows:
    I am running regressions with different independent variables := xvars and dependent variables := yvars. For this purpose, I store them in locals.
    Utilizing a "foreach"-statement, I loop through all of the independent and dependent variables.

    I would like to retrieve the number the loop currently stands at in terms of the independent variables (in order to write it in the heading of a table I esttab).

    Example:
    2 independent variables x1-x2,
    5 independent variables y1-y5,
    resulting into 10 combinations:

    reg y1 x1
    reg y2 x1
    ...
    reg y5 x1
    reg y1 x2
    reg y2 x2
    ...
    reg y5 x2

    This is how I were to implement this example:
    Code:
    local     xvars     x1 x2
    local     yvars     y1 y2 y3 y4 y5
    
    foreach x_i of local xvars {
    foreach y_i of local yvars {
    eststo `y_i': quietly reg `y_i' `x_i'
    }
    esttab `yvars' using Z:\STATA\output\notsorted\reg_out.html, title(`x_i') append
    }
    If you were to consider this code example, please, what I would like to achieve is having the number of element in the xvars-local for the outer xvars-loop in the title instead of the string of the element in the local the loop currently prevails at.


    Yours sincerely,
    Mario

  • #2
    Mario, you wrote:

    what I would like to achieve is having the number of element in the xvars-local for the outer xvars-loop in the title
    Here it is:
    Code:
    local     xvars     x1 x2
    local     yvars     y1 y2 y3 y4 y5
    
    local index=0
    
    foreach x_i of local xvars {
      local `index++'
      
      foreach y_i of local yvars {
        //eststo `y_i': quietly reg `y_i' `x_i'   // not essential for the example
      }
      //esttab `yvars' using Z:\STATA\output\notsorted\reg_out.html, title(`x_i') append // not essential for the example
      display `index'
    }
    Use local index inside the loop.

    Best, Sergiy

    Comment


    • #3
      Hello Sergiy,

      thank you very much - exactly what I was looking for.
      Further, I would like to apologize for having blown up my case unnecessarily - luckily, you took the time to read through it to distill the issue of mine.

      Yours sincerely,
      Mario

      Comment

      Working...
      X