In Stata, how can I append to a local varlist during a loop?

Drew picture Drew · Apr 2, 2015 · Viewed 7.5k times · Source

I am trying to run multiple regressions where, on each iteration, another independent variable is added to the regression on each loop?

local vlist0 foo bar dar
local vlist1

foreach item in `vlist0'
    [add `item' to `vlist1']
    regress dependentVar `vlist1'

I can't seem to find any documentation on appending to local varlists or anything relating to this, so your help is greatly appreciated.

Thanks!

Answer

Roberto Ferrer picture Roberto Ferrer · Apr 2, 2015

Some technique:

local vlist0 foo bar dar

local vlist1
foreach item of local vlist0 {
    local vlist1 `vlist1' `item'
    display "`vlist1'"
}

This appends the contents of the local, along with the new item, to the local itself.

Notice what this really does: redefine local vlist1 each time around the loop. The new definition is the previous definition, plus the new item. The first time around the loop vlist1 is empty, but that is not illegal and is well-behaved.