Bookmark and Share

Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at statalist.org.


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: st: From: "Katie and Matt O'Varanese" <[email protected]>


From   "Longton, Gary M" <[email protected]>
To   [email protected]
Subject   Re: st: From: "Katie and Matt O'Varanese" <[email protected]>
Date   Tue, 23 Nov 2010 15:18:03 -0800 (PST)

you wrote:

Okay, I'm very new -- I need to add some leading zeros before using
the numbers before re-stringing them.  Right now, the numbers are used
as an ID and are supposed to be 3 digits long -- but if its "2" then
it just has "2" I want "002" ...

how??

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

It's not completely clear from your question whether your id variable is currently of numeric or string type, nor is it clear which type you wish to end up with, though my guess is that you would like to end up with a string type variable.

a) if you have a numeric id variable and just wish to have it display as a 3 digit integer with leading zero's, change the display format accordingly (see -help format-), eg.

  .clear
  .set obs 20
  .gen id = _n
  .format id %03.0f
  .list id
  
b) if you have a numeric id variable and wish to change it to a 3 digit string with leading zeros included, use the -string(n,s)- function (see -help string functions-)

  .gen id_str = string(id,"%03.0f")
  .list id id_str
  
c) if you have a string id variable that does not include leading zeros, you can use the same approach as in (b), with the added intermediate step of converting from string to numeric type:

  .gen id2 = string(_n)  //  results in a string id with 1 or 2 digits
  .gen id2_str = string(real(id2),"%03.0f")
  .list id2 id2_str
  
- Gary


*
*   For searches and help try:
*   http://www.stata.com/help.cgi?search
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/


© Copyright 1996–2018 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   Site index