Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

foreach using numlist of numbers with leading 0s

In Stata, I am trying to use a foreach loop where I am looping over numbers from, say, 05-11. The problem is that I wish to keep the 0 as part of the value. I need to do this because the 0 appears in variable names. For example, I may have variables named Y2005, Y2006, Var05, Var06, etc. Here is an example of the code that I tried:

foreach year of numlist 05/09 {
   ...do stuff with Y20`year` or with Var`year`
}

This gives me an error that e.g. Y205 is not found. (I think that what is happening is that it is treating 05 as 5.)

Also note that I can't add a 0 in at the end of e.g. Y20 to get Y200 because of the 10 and 11 values.

Is there a work-around or an obvious thing I am not doing?

like image 843
bill999 Avatar asked Dec 05 '25 13:12

bill999


1 Answers

Another work-around is

forval y = 5/11 { 
     local Y : di %02.0f `y' 
     <code using local Y, which must be treated as a string> 
}

The middle line could be based on

 `: di %02.0f `y'' 

so that using another macro can be avoided, but at the cost of making the code more cryptic.

Here I've exploited the extra fact that foreach over such a simple numlist is replaceable with forvalues.

The main trick here is documented here. This trick avoids the very slight awkwardness of treating 5/9 differently from 10/11.

Note. To understand what is going on, it often helps to use display interactively on very simple examples. The detail here is that Stata is happily indifferent to leading zeros when presented with numbers. Usually this is immaterial to you, or indeed a feature as when you appreciate that Stata does not insist on a leading zero for numbers less than 1.

. di 05
5

. di 0.3
.3

. di .3
.3

Here we really need the leading zero, and the art is to see that the problem is one of string manipulation, the strings such as "08" just happening to contain numeric characters. Agreed that this is obvious only when understood.

like image 139
Nick Cox Avatar answered Dec 07 '25 15:12

Nick Cox