Announcement

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

  • Removing the last digit of a variable with unequal length

    Hi Statalist!

    I have a variable (int format) and I would like to create another variable that removes the last digit of said variable.

    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input int ward
    141
     31
    171
    133
    173
    311
    381
     91
    101
    291
    101
    111
    113
    123
    243
     91
    103
    132
    142
     13
     13
     21
    103
     61
    121
    141
     41
     73
    143
    233
     21
    141
    311
     41
    103
    132
    151
    271
     41
     83
    121
     91
    341
    241
     22
    101
     31
    171
    193
    111
     83
    341
    181
     83
    101
     53
     71
     22
     93
     93
    193
     83
     91
    111
     62
    123
     51
    131
    101
    123
    123
     71
     12
     42
     42
     62
     72
     82
     92
     92
    112
    152
    232
    242
    242
     62
    102
    202
     12
    102
    132
    182
    192
    212
    222
     11
     61
     81
    161
    183
    end
    So if ward is equal to 141, I would like the new variable to be 14. If ward is equal to 92, I would like the new variable to equal 9.
    The ward variable is either 2 digits or 3 digits long.

    Any tips on how I can do this?
    Do I have make ward into a string variable and then use subinstr() or substr?

    Many thanks!
    Kevin

  • #2
    You may try this code:

    Code:
    gen newvar = round(ward/10)
    Best regards,

    Marcos

    Comment


    • #3
      Marcos Almeida - Thank you so much! Your code does the trick.

      Comment


      • #4
        Strictly, floor(ward/10) always drops digits while round() will do that only sometimes.

        Comment


        • #5
          Nick Cox ' s code, as always, is the best one.

          Just for the sake of giving alternatives, there is also the int() function, which will do fine in this particular case as well, as shown by the - assert - command.

          Code:
          gen var1 = round(ward/10)
          gen var2 = floor(ward/10)
          gen var3 = int(ward/10)
          assert var1 == var2
          assert var2 == var3
          assert var1 == var3
          Best regards,

          Marcos

          Comment


          • #6
            Thank you both for your feedback.
            I appreciate your help.

            Kevin

            Comment

            Working...
            X