Announcement

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

  • Split numeric

    Greetings all,

    Suppose I have variable X that I want to convert to X1 and X2 as follows:
    X X1 X2
    123 12 3
    456 45 6
    7890 789 0
    So basically I want to take X and make two new variables- variable X2 has only the last character of X and variable X1 has all but the last character of X.

    I tried to split string but am not able to get it to do this. Please advise, thanks so much!

  • #2
    Code:
    clear 
    input X    X1    X2
    123    12    3
    456    45    6
    7890    789    0
    end 
    
    gen work = string(X, "%12.0f")
    gen x1 = real(substr(work, 1, length(work) - 1)) 
    gen x2 = real(substr(work, -1, 1)) 
    
    list 
    
        +-----------------------------------+
         |    X    X1   X2   work    x1   x2 |
         |-----------------------------------|
      1. |  123    12    3    123    12    3 |
      2. |  456    45    6    456    45    6 |
      3. | 7890   789    0   7890   789    0 |
         +-----------------------------------+
    Note that the format argument here %12.0f is pulled out of the air and

    1. would not be needed if your real data were all like your example.

    2. might need to be different for longer numbers.

    Comment


    • #3
      So perfect thank you !

      Comment


      • #4
        Other solution:
        Code:
        gen X1=floor(X/10)
        gen X2=X-X1*10

        Comment


        • #5
          Romalpa: Indeed, if we can assume, as the example seems to imply, that the string contains integer equivalents.

          Note -- with the same assumption -- that mod(X, 10) is an alternative for the last numeric character.

          Comment

          Working...
          X