Why this behaviour?
In essence, -forvalues- expects a range, as defined
by example in its syntax diagram. What is not quite
spelled out in that syntax diagram is that all the elements
of the range must be explicit.
So
forval i = 1/_N {
...
}
doesn't qualify. _N is not explicit enough; you are
expecting Stata to evaluate _N. It is happy enough
to do that in other contexts, but not this one.
forval i = 1/`=_N' {
...
}
is a work-around. Stata's parser catches `=_N' and evaluates
it and passes the result to -forvalues-, so what -forvalues-
actually sees is 1/74, or whatever. This feature was introduced
in Stata 7, but not documented until Stata 8.
-display- is different, as part of its job is to evaluate
before displaying.
A quite different comment is that almost all loops over observations
can be avoided, but I can't say whether your problem is like that.
Nick
n.j.cox@durham.ac.uk
John Wallace
> I have a problem using a forval loop to assign values to a
> numeric variable
> (for brevity, assume that -encode- doesn't work here). I
> want to loop
> through the entire dataset, addressing each value in turn, so
>
> .forval e = 1/_N
>
> would appear to be the appropriate form. I get an "invalid
> syntax" error
> when I do so.
>
> .di _N
>
> gives me the expected result for this dataset, 2339.
>
> .forval e = 1/2339
>
> works as expected.
> How am I screwing this up?
Fred Wolfe
> This will work:
>
> forval e = 1/`=_N'
Nichols, Austin
> That's a very handy tool, indeed. Cf.
>
> #delimit;
> forval e = 1/5 {; di `e'; };
> forval e = 1/2+3 {; di `e'; };
> forval e = 1/`=2+3' {; di `e'; };
>
> where the second example bombs for the same (?) reason
> as forval e = 1/_N but the third runs fine.
*
* 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/