Statalist The Stata Listserver


[Date Prev][Date Next][Thread Prev][Thread Next][Date index][Thread index]

Re: st: How can I add leading zeros conditionally?


From   Joseph Coveney <[email protected]>
To   Statalist <[email protected]>
Subject   Re: st: How can I add leading zeros conditionally?
Date   Fri, 17 Feb 2006 13:41:08 +0900

Ainsley Charles wrote (excerpted):

Reg is consistently a str2 but ed is not (at most,
though, it's a str5). I wish my new variable to be a
str7 of the form "1000100", "1103200", and "1216400"
for the examples provided. So, for ed, I need to add
two leading zeros to the first observation and one to
the second. Then I need to create the new variable.

--------------------------------------------------------------------------------

In addition to the -tostring- command, there is also a -string()- function.
With the function, you can combine into one command the string contatenation
shown by Germ�n Rodriguez and to-string-conversion with leading-zero
formatting shown by Maarten Buis, that is, do the conversion in one fell 
swoop.

You can also use string concatentation to insert a spacer, such as a hyphen
or any other string character, in order to make long ID numbers more
readable or less error-prone when you're scanning through data listings.

Joseph Coveney

clear
set more off
input byte region_number int enumeration_district_number
10      100
11     3200
12    16400
end
* The next line shows the use of -string()- and
* string concatentation to do both at once.
generate str unique_identifier = ///
  string(region_number, "%2.0f") + "-" + ///
  string(enumeration_district_number, "%05.0f")
* You can decide whether the hypen improves readability
* of the unique identifiers
local variable_name_length = 0
foreach var of varlist _all {
    local variable_name_length = //
      max(`variable_name_length', length("`var'"))
}
list , noobs abbreviate(`variable_name_length') separator(0)
exit

*
*   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