Stata The Stata listserver
[Date Prev][Date Next][Thread Prev][Thread Next][Date index][Thread index]

Re: st: Loop trouble


From   Nick Cox <[email protected]>
To   [email protected]
Subject   Re: st: Loop trouble
Date   Fri, 09 May 2003 17:08:39 +0100

Huiber Gabi 

> I'm trying to run a loop like this:
> 
> use "`mytempfile'"
> local x _N
> forvalues i(1)`x' {
> [do stuff]
> }
> 
> This loop is identical to the one in the Programming Manual, p. 106,
where
> the loop 
> 
> local n 3
> forvalues i(1)`n' {
> [do stuff]
> }
> 
> will run just fine three times. Mine claims that the syntax is
invalid. Any
> ideas?

The reference is to [P] for _version 7_. First, where you have 

forvalues i(1)`n' 

you should have 

forvalues i = 1(1)`n' 

Beyond that, your syntax is invalid for another reason. Your 

local n _N 

just copies the text "_N" into the macro; it does not evaluate _N. You
want the number represented by _N to go into the macro. 

The example in the manual trades on the ambiguity of 

3

which in some contexts is the character "3" and in other contexts is
the number 3. Usually, Stata is smart and makes the right decision. In
other contexts, it does not matter. Thus 

di 3 

and 

di "3" 

have the same result, so far as the user is concerned. However, 

di _N 

and 

di "_N" 

are not equivalent. But where -display- _does_ do some evaluation, 
-forvalues- in version 7 did none. 

Anyway, 

use "`mytempfile'"
local x = _N
forvalues i = 1(1)`x' {
	[do stuff]
}

will solve the problem. In Stata 8, this will also work: 

use "`mytempfile'"
forvalues i = 1(1)`=_N' {
	[do stuff]
}

Incidentally, over time keystrokes will be saved by writing 

1/`n'

rather than 

1(1)`n' 


Nick
[email protected]
*
*   For searches and help try:
*   http://www.stata.com/support/faqs/res/findit.html
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/



© Copyright 1996–2024 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   What's new   |   Site index