[email protected] wrote:
> Suppose I have a string variable with 3 position on each observations.
> Each of these observations contains some values range from 1-999.
> i.e.:
> X
> obs1 1
> obs2 12
> obs3 123
> (though all entries are numerical, but variable X is of string format)
>
> My purpose is to reconstruct this variable to be the following formate:
> X
> obs1 001
> obs2 023
> obs3 345
>
> i.e. I want to replace the left postition for each observation with "0" if
> nothing here.
A somewhat less complicated solution than those that have been proposed:
If want to end up, as you started, with a string format variable, this
can be achieved in one line by combining the string(n,"%fmt") and real()
functions:
replace x = string(real(x),"%03.0f")
see on-line help for string functions (whelp strfun) and for display
formats (whelp format)
If, on the other hand, you prefer to work with this as a numeric
variable but wish to display with leading zeros, then just convert to a
real and format to display accordingly (i.e identical to the above
solution, but eliminate the outer string() function:
gen x2 = real(x)
format x2 %03.0f
- Gary
*
* 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/