Nick,
I was sloppy in the e-mail, not in the original code. Also, initially I used
forvalues i=1/`x'
to no avail. So I switched to the programming manual's less elegant
forvalues i=1(1)`x'
out of desperation.
Anyway, here's a strange ambiguity:
Suppose mytempfile has 17 observations. The code
use "`mytempfile'"
display _N
local x _N
display `x'
will have the same effect as
use "`mytempfile'"
display _N
local x=_N
display `x'
The effect is that the display command will twice show the right number, 17,
in both cases.
The difference between two slabs of code is that
forvalues i=1/`x'
does not work after the first, but works fine after the second.
In other words, the equal sign makes no difference to the value of the local
variable x, yet it does matter to forvalues.
Thanks for your help. I'm all sorted now.
Gabi
-----Original Message-----
From: Nick Cox [mailto:[email protected]]
Sent: Friday, May 09, 2003 12:09 PM
To: [email protected]
Subject: Re: st: Loop trouble
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/
*
* 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/