,

Using locals and loops to generate long strings

The following command can be used to generate a command which consists of several new variables which are generated within a loop. This could either be done by (e.g. generating a number of log variables) gen newvar1 = log(var1) gen newvar2 = log(var2) etc. reg depvar newvar1 newvar2 If there are more variables to generate,…

The following command can be used to generate a command which consists of several new variables which are generated within a loop.

This could either be done by (e.g. generating a number of log variables)
gen newvar1 = log(var1)
gen newvar2 = log(var2)
etc.

reg depvar newvar1 newvar2

If there are more variables to generate, it can be more handy to use the following commands

local command = ""
local loc = "var1 var2" /* this local contains all original variables */
foreach var of local loc {
gen new`var' = log(`var')
local command = " `command' new`var' "
}
di "`command'"

The new local-macro command now contains all new variables
newvar1 newvar2 and can be used in any commands.

Tags:

Response to “Using locals and loops to generate long strings”

  1. Emily

    Thank you! Thank you! I have been all over the internet in Stata forums and could not figure how to concatenate long strings >255 characters into a local until I found your blog. In my case I had to make a bunch of dummy variable values, each for 1 of 10 periods to post to a Monte Carlo simulation to graph later. Here, is a variation of what I did that may hopefully help others:
    local loc “”
    foreach result in EY_group1_t EY_group2_t ///
    EY_group3_t EY_group2_t {
    forval t=1/20 {
    local loc “`loc’ `result’`t’ ”
    }
    }
    di “`loc’”

Leave a Reply