Search code examples
loopsconditional-statementsstatadisplay

Display or print loop variable for debugging purposes


ID  A1  A2  A3
1001    ABD AAA ABC
1002    ABE BBB CCC
1003    ABC CCC DDD

I have a loop as follows:

generate trackr = 0
display "generated trackr"
foreach var of varlist a1 a2 a3{
    display "`var'" id[_n]
    replace trackr = 1 if (`var'=="ABC")
}

In Stata, I would like to find out and print when a change has been made to trackr. (I want to find out in which row/column "ABC" was discovered.)

I tried the above id[_n] and it works only partially.

I would like to display id[_n] ONLY if var=="ABC" and trackr changes to 1 (from 0). I tried putting everything in an if block, but I think if in Stata works differently?


Solution

  • You don't need a loop for what you appear to want. See dataex from SSC for a better way to give example data in Stata questions.

    clear
    input ID  str3 (A1  A2  A3) 
    1001    ABD AAA ABC
    1002    ABE BBB CCC
    1003    ABC CCC DDD
    end 
    
    gen trackr = inlist("ABC", A1, A2, A3) 
    list if inlist("ABC", A1, A2, A3) 
    
         +---------------------------------+
         |   ID    A1    A2    A3   trackr |
         |---------------------------------|
      1. | 1001   ABD   AAA   ABC        1 |
      3. | 1003   ABC   CCC   DDD        1 |
         +---------------------------------+
    

    Here inlist() yields 1 if any of the second and later arguments is equal to the first argument and 0 otherwise.

    In your loop something like display A1[_n] will only show values in the first observation, as you loop over variables, but not observations. But no loop is needed.

    If you wish to see just the first observation that satisfies your criterion, one way to do that is

    . list if trackr & sum(trackr) == 1
    
         +---------------------------------+
         |   ID    A1    A2    A3   trackr |
         |---------------------------------|
      1. | 1001   ABD   AAA   ABC        1 |
         +---------------------------------+
    

    and it follows that list if sum(inlist("ABC", A1, A2, A3)) == 1 would also work to find the first such observation.