Search code examples
loopsstatainteraction

Clarification for a loop to create interaction terms in Stata


I found the following question/answer that I think does what I would like to do: https://www.stata.com/statalist/archive/2009-09/msg00449.html

However, I am unclear what is going on in all of it, and would like to understand better. The code for the solution is as follows:

unab vars : var1-var30
local nvar : word count `vars'
forval i = 1/`nvar' {
  forval j = 1/`=`i'-1' {
    local x : word `i' of `vars'
    local y : word `j' of `vars'
    generate `x'X`y' = `x' * `y'
  }
}

I do not understand what is going on in line 4 with the statement: ``=i'-1'.

The i refers to the number in the set {1,...,n}, but I do not understand what the equals or the -1 are doing. My assumption is that the -1 is somehow removing the own observation, but I am unclear. Any explanation would be appreciated.


Solution

  • Suppose you have local macro i that varies over a range and you want its value minus 1. You can always do this

      local j = `i' - 1 
    

    and then refer to j. You can also do this on the fly:

     `= `i' - 1' 
    

    Within

     `=   ' 
    

    Stata will evaluate the expression, here

    `i' - 1 
    

    and substitute the result of that expression in a command line.

    You can do this with scalars too:

    scalar foo = 42 
    

    and then refer to

    `= foo' 
    

    However, watch out. Scalar names and variable names occupy the same namespace.

    `= scalar(foo)' 
    

    disambiguates and arguably is good style in any case.