Announcement

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

  • real-function: Telling STATA to keep zero

    Hey everyone,

    I have the following question out of curiosity, as I will solve it another way but would be interested whether the following is possible:

    I have postal codes, where some are starting with a 0. I would like to convert string into numeric.
    Using the real- function I get the following problem:

    Code:
     1665 "01665"
     1665 "01665"
     1665 "01665"
    33154 "33154"
    33154 "33154"

    As one can see the numeric values are now wrong as some would have to start with a zero which the real-function does not count.

    Does anybody know how to solve this problem without going an other way.

    Would be interested in any ideas.

    Thanks and best wishes
    Tobi

  • #2
    The number 1665 is mathematically identical to 01665 so the numeric values are not wrong in any sense. This is a matter of display format

    Code:
    display %05.0f 1665
    yields

    Code:
    . display %05.0f 1665
    01665
    Best
    Daniel

    Comment


    • #3
      Numeric values cannot truly have leading zeros. If you want leading zeros in the actual data, you need to save them as a string. At least in my understanding. You can pretend there's a leading zero by using display formats, but you have to keep in mind that the zero won't actually be there.

      Code:
      clear
      set obs 1
      gen codeS = "01234"
      destring codeS, gen(code)
      format code %05.0f
      gen zeroSpotted = 1 if code == 01234
      br
      Note that it doesn't actually matter, because in code the zero gets ignored as well. So it is perfectly fine to write leading zeroes in your code (0123 is equal to 123), this is true regardless of whether you specify the display format.

      Comment


      • #4
        In addition to excellent advice already received: note that it may be that encode rather than real() is what you need here.

        Comment


        • #5
          Thanks for the great tips and insights, I now to have the data in strings, yet otherwise Nick is right that encode does the trick.

          Best
          Tobi

          Comment

          Working...
          X