Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Leading zero

    Hi statalist community,


    Code:
    * Example generated by -dataex-. For more info, type help dataex
    clear
    input  RTR
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    end


    What I need, is to put leading zero in single digit number-

    Needed output looks like.

    RTR
    01
    02
    03
    04
    05
    06
    07
    08
    09
    10
    11
    12
    13
    14
    15
    16
    17


  • #2
    Ajay:
    I can figure the issue this way:
    Code:
    . tostring RTR, g(string_RTR)
    string_RTR generated as str2
    
    . g butler=0
    
    . egen wanted=concat(butler RTR) if RTR<=9
    
    . replace wanted= string_RTR if wanted==""
    
    . keep wanted
    
    . list
    
         +--------+
         | wanted |
         |--------|
      1. |     01 |
      2. |     02 |
      3. |     03 |
      4. |     04 |
      5. |     05 |
         |--------|
      6. |     06 |
      7. |     07 |
      8. |     08 |
      9. |     09 |
     10. |     10 |
         |--------|
     11. |     11 |
     12. |     12 |
     13. |     13 |
     14. |     14 |
     15. |     15 |
         |--------|
     16. |     16 |
     17. |     17 |
         +--------+
    
    .
    Kind regards,
    Carlo
    (Stata 19.0)

    Comment


    • #3
      If you want to see leading zeros in output but keep underlying values identical use format.

      If you want a string with leading zeros for single digits, you can use strofreal() directly.

      Code:
      clear 
      set obs 12 
      gen have = _n 
      
      format have %02.0f 
      
      gen wanted = strofreal(have, "%02.0f")
      
      list 
      
           +---------------+
           | have   wanted |
           |---------------|
        1. |   01       01 |
        2. |   02       02 |
        3. |   03       03 |
        4. |   04       04 |
        5. |   05       05 |
           |---------------|
        6. |   06       06 |
        7. |   07       07 |
        8. |   08       08 |
        9. |   09       09 |
       10. |   10       10 |
           |---------------|
       11. |   11       11 |
       12. |   12       12 |
           +---------------+

      Comment


      • #4
        Thank you Carlo and Nick.

        Comment

        Working...
        X