Hello All,
  • I have 30 pairs of variables from which I need to derive 30 new variables.
  • I'd like to use a loop (e.g., foreach with gen and replace) to streamline the script. But I am struggling with how to specify the unique sets of vars (*_new, *_cor, and *_free ) involved in each iteration( e.g., substituting a wildcard for the numeric element of the var names is not unique across the 30 sets)
  • A sample of my script for deriving each new var individually follows:
Code:
gen Q1a_new = 2  if(Q1a_cor == 1 & Q1a_free == 1) , after(Q1a_free)
     replace Q1a_new = 1  if(Q1a_cor == 1 & Q1a_free == 2)
     replace Q1a_new = 0  if(Q1a_cor == 0)

gen Q2a_new = 2  if(Q2a_cor == 1 & Q2a_free == 1) , after(Q2a_free)
     replace Q2a_new = 1  if(Q2a_cor == 1 & Q2a_free == 2)
     replace Q2a_new = 0  if(Q2a_cor == 0)

gen Q3a_new = 2  if(Q3a_cor == 1 & Q3a_free == 1) , after(Q3a_free)
     replace Q3a_new = 1  if(Q3a_cor == 1 & Q3a_free == 2)
     replace Q3a_new = 0  if(Q3a_cor == 0)
I am using Stata 14.2 on Windows 10.
  • FYI - I know how to use foreach for loops in general. Also, foreach using calls to (saved) local macros for when the varlist needs to be used repeatedly,. But in this case I do not need to repeat the sequence once the 20 derived vars are created.
Much thanks for your suggestions.

wg