Statalist The Stata Listserver


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

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


From   n j cox <[email protected]>
To   [email protected]
Subject   Re: Re: st: How can I add leading zeros conditionally?
Date   Fri, 17 Feb 2006 14:07:46 +0000

Let me add one comment to Joseph's characteristically
lucid and detailed explanation.

-string()- and -tostring- are really the same idea at
two different levels.

The -string()- function is more fundamental, and does
the hard work of converting numbers to strings.

The -tostring- command is, from one point of view,
a wrapper for -string()-, as may be seen by glancing
at the code:

. viewsource tostring.ado

The difference -tostring- makes is twofold: convenience
and protection. You can process several variables at
one and there are some safeguards inhibiting you from
doing some dopey things.

Nick
[email protected]

>>> Joseph Coveney

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.

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