1

I am new to programming in Stata. My question is to run several pairs of regressions in a loop, like the following:

reg outcome1 outcome2 covariates
reg outcome2 outcome1 covariates

I tried the following ways, but the first two came with the error "ambiguous abbreviation" and the second the error "too few variables specified". Can anyone help me to fix it?

foreach dv in x y z {
        local outcome1 = `dv' + "1"
        local outcome2 = `dv' + "2"
        reg `outcome1' `outcome2' covariates
        reg `outcome2' `outcome1' covariates
}

foreach dv in nduration nsleep nwaso nlatency nfragmentation npctsleep {
        gen outcome1 = `dv' + "1"
        gen outcome2 = `dv' + "2"
        reg `outcome1' `outcome2' covariates
        reg `outcome2' `outcome1' covariates
}

foreach dv in x y z {
        reg `dv'1 `dv'2 covariates
        reg `dv'2 `dv'1 covariates
}
2
  • Your other questions indicate that you have installed R. What you are trying to do would necessitate a bit of wrangling in R, but it's pretty straightforward in Stata (Nick has the full answer below). Welcome to Stata :) Commented Sep 1, 2013 at 10:20
  • Thanks! I am happy to be on the way of learning Stata programming. Commented Sep 1, 2013 at 12:26

1 Answer 1

3

What you are asking is unclear, as your third solution should work, so long as you spell out the covariate names.

Concatenation here is just juxtaposition, but you need to concatenate names as strings. You don't need to create macros in your example.

foreach dv in x y z {
    reg `dv'1 `dv'2 covariates
    reg `dv'2 `dv'1 covariates
}

The second solution is wrong, as from Stata's point of view you are trying to add a numeric variable and a literal string in each generate command.

The first solution would be better with lines like

local outcome1  "`dv'1"

which makes the string manipulation explicit, but as above you don't need this extra macro.

This should also work

local outcome1 = "`dv'" + "1"

The points to remember here (until they become known without effort) are that

  1. Macro manipulation provides a way of working on variable names, not variable contents.

  2. Stata does all macro substitution before trying to execute a command.

I wrote http://www.stata-journal.com/sjpdf.html?articlenum=pr0005 as a tutorial review of loops in Stata, including use of local macros.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much for your answer and tutorial! They are pretty helpful and comprehensive!
@Randel W Thanks. There is a lot of expository material in the Stata Journal; all that which is 3+ years old is publicly accessible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.