Announcement

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

  • Get no. of times for loop has iterated

    Is there a way that I can access the number of times a given loop is on. For example,

    Code:
    sysuse auto
    foreach var in weight price mpg rep78 {
    
        /*1. Tabulate the variable*/
         tab `var'
    
         /*2. The no. of times this loop has iterated*/
         local iteration_no =
         di `iteration_no'
    }
    Where the desired output would be

    Code:
    A tabulation of weight
    
    1
    
    A tabulation of price
    
    2
    
    A tabulation of mpg
    
    3
    
    A tabulation of rep78
    
    4
    How can I define iteration_no to return the desired output. Thank you very much for your help.
    Last edited by Jack Reimer; 07 Aug 2019, 07:59.

  • #2
    Code:
    sysuse auto
    local iteration_no = 0
    foreach var in weight price mpg rep78 {
         local iteration_no = `iteration_no' + 1      // local ++iteration_no would be more "Stata-ish"
        /*1. Tabulate the variable*/
         tab `var'
         /*2. The no. of times this loop has iterated*/
         di `iteration_no'
    }

    Comment

    Working...
    X