1

I am currently creating a loop which will run a regression for different regions. The regression I am trying to run is:

reg x1 x2 x3 if Region==n

where n=1,2,3,4,5,6.

Running them separately by manually typing is fine but when trying to run the following loop I've written:

local Region "1 2 3 4 5 6"
foreach i of local 'Region' {
reg x1 x2 x3 if Region== 'i'
}

it reports the error:

 'i' invalid name
r(198);

Can anyone suggest some advice to remedy this error?

1
  • 1
    foreach i of local 'Region' should be foreach i of local Region. Also, you can omit " " while defining local. Commented Aug 26, 2014 at 15:24

1 Answer 1

5

The problem reported is not to do with foreach or regress, but with your use of local macros.

The left and right quotation marks around local macro references differ. Otherwise macro references could not be nested, which would be a severe problem. This is documented, e.g. [U] 18.3.1 in PDF documentation.

There are other problems with your code. Let's fix it first, using the correct quotation marks and fixing another syntax error:

local Region "1 2 3 4 5 6"
foreach i of local Region {
    reg x1 x2 x3 if Region == `i'
}

The assumption here is that you have a variable called Region and you are also defining a local macro with the same name. If that's true and some other assumptions are true, the above should work. Note how the macro name is not referenced in the call to foreach.

Note incidentally that this example can be simplified. Defining a local macro here is like putting objects into a bag only to take them out immediately afterwards. You don't need to do that.

foreach i in 1 2 3 4 5 6 {
    reg x1 x2 x3 if Region == `i'
}

Further, when the list is this simple, you can use forvalues instead:

forval i = 1/6 {
    reg x1 x2 x3 if Region == `i'
}

All that aside, check out statsby to see if it helps.

In summary:

  1. Syntax error: Use different quotation marks in referring to local macros.

  2. Syntax error: In looping with foreach over the elements of a local macro, name it, don't reference it.

  3. Style error: Don't use local macros you don't need.

  4. Style error: Use forvalues instead of foreach when it's equivalent.

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

2 Comments

Many thanks, the style and syntax errors are duly noted. May I ask, if I am using the 'forvalues' instruction and I want to carry out a seperate regression for each country, is there a way of telling Stata that I want to loop this regression across all "i" instead of specifying the values of "i"?
That's an FAQ: stata.com/support/faqs/data-management/… Note that search foreach in Stata would have pointed to it.

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.