Announcement

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

  • Removing the first number on a numeric variable

    Please help. I have a zip code variable but they all start with the number "5". How do I remove the "5"?
    Here is the example:
    500601
    500602
    500603
    500606
    I want to be able to have 5-digit zip codes with the five at the beginning removed; as '00601, 00602, 00603, 00606'

    Thanks

  • #2
    Check whether it is not already a string, if it is not,

    Code:
    . tostring var, replace
    var1 was long now str6
    
    . gen five = substr(var,2,5)
    if it is already a string, directly the second step.

    Comment


    • #3
      Thank you Joro! Worked perfect

      Comment


      • #4
        tostring can be cut even if the conversion is needed. Consider

        Code:
        gen wanted = substr(string(var), 2, 5)

        Comment


        • #5
          Thanks Joro and Nick!
          Please help, in a situation where i have state codes (234) and individual codes (1001). How do I remove the "234"?
          Here is the example:
          2341001
          2341005
          2341800
          2341700

          Instead of the above, I want to be able to have codes as "1001, 1005, 1800, 1700"

          Thanks

          Comment


          • #6
            Your example in #6 leaves ambiguous whether the variable concerned is numeric or string. This is why we ask people to use dataex.

            Code:
            clear 
            input long mynumvar str7 mystrvar 
            2341001 "2341001"
            2341005 "2341005"
            2341800 "2341800"
            2341700 "2341700"
            end 
            
            gen wanted1 = mod(mynumvar, 10000)
            gen wanted2 = substr(mystrvar, 4, 4)
            
            list
            Results

            Code:
            . list 
            
                 +-----------------------------------------+
                 | mynumvar   mystrvar   wanted1   wanted2 |
                 |-----------------------------------------|
              1. |  2341001    2341001      1001      1001 |
              2. |  2341005    2341005      1005      1005 |
              3. |  2341800    2341800      1800      1800 |
              4. |  2341700    2341700      1700      1700 |
                 +-----------------------------------------+

            Comment


            • #7
              Thank you so much Nick, It worked perfectly

              Comment

              Working...
              X