Statalist The Stata Listserver


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

st: Padding zeros, writing functions


From   "Ari Friedman" <[email protected]>
To   <[email protected]>
Subject   st: Padding zeros, writing functions
Date   Wed, 24 Jan 2007 15:33:42 -0500

Hi everyone,

  It occurred to me today that the way that I pad numbers out to a certain
number of digits is a bit annoying.  Generally, I -tostring- the variable,
then generate a new variable with 0000's in front, then -substr- from with a
negative starting position.  This works fine.  However, I'd like to write a
pad() function that handles things without the fuss.

  But then I realized that I don't know how to write functions.  ADO files,
sure.  But things like the built-in functions substr(), string(), etc. I
have no clue how to program.

Ideally I want to have a function that can be used like:
- gen county_code = pad(county_number,3,"0") -
Where 3 is the number of digits to pad to (e.g. 1 becomes 001, 15 becomes
015, and 387 stays 387), and "0" is the digit or character to do the padding
with (default to zero).

It's not too difficult to do this manually, but it'd be nice to have a
simple function.  The closest to a one-liner I've come is:
replace state = "0" + regexs(0) if regexm(state, "^[0-9]$")

But that's a bit bulkier than I'd like.




So my questions are these:
1) Is there a good padding function already written?
2) Can someone give me a pointer to the part of the Stata documentation that
explains how to write functions (as opposed to ADO commands)?  I've looked
several times, but I have been known to miss obvious things before....

Thanks as always,
Ari


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