Thursday, February 16, 2006

st: How can I add leading zeros conditionally?

Hello Statalisters,

From what I've seen it's a convention to announce oneself as a newbie when posting one's first question, so there it is.

How do I add leading zeros to a string variable conditional on its length? My objective is to create a unique identifier, say id, by combining the elements of two variables, region and edno (that's enumeration district number). These variables were originally numerics so, to begin, I -tostring-ed them and created new variables reg and ed. My data are of the form:

reg ed 10 100 11 3200 12 16400

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.

I reviewed the FAQ and -search-ed "leading zeros" (I looked at Nick Cox's "Removing leading..." for ideas that might be implemented in the reverse; also Gary Peterson's "Is there a way..."). Because I must only change ed when it's of less than 5 characters, however, I am unsure what to do. Any thoughts would be greatly appreciated.

By the way, I'm using Stata/SE 9.1 for Windows, born on 20 January 2006. Plus I'm on the digest so forgive me if I don't respond immediately.

Cheers,

Ainsley Charles

__________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com * * 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/


Tag:


Links to this post:

Create a Link



<< Home

This page is powered by Blogger. Isn't yours?