Announcement

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

  • Extracting the first number from a numeric variable into a new variable

    Hi,

    I would like to extract the first number of another variable into a new variable. (And an additional one which contains the first and the second number if there is one)
    The existing variable has different length in its values:
    e.g.
    911
    9313
    61
    521
    1
    ...
    I would like to create a new variable containing only the first number from each observation
    -> meaning:
    9
    9
    6
    5
    1

    It would be great if anyone had a solution, with which it is not necessary to convert it to a string first (if seen a lot of solutions which do that), because I wanna use it as a numeric variable.

    + another solution which does not work for me (because not all observations have the same length) is this one:

    the variable containing the numbers mentioned above is called "ISCO"

    gen twodigit_ISCO=int(ISCO/100)


    Does anyone have any suggestions?
    Thanks in advance!!
    Clara

  • #2
    You've accidentally posted in the area for practicing posts ("... the forum software"), not the area for Stata questions. Generally speaking, people don't read this section, so in the future you'll want to post in the Stata section.

    The easiest and safest solution is the one involving strings. Your concern about "wanna use it as a numeric variable" is misplaced, as you can simply convert the string result back to a number.

    Code:
    clear
    input yournum
    911
    9313
    61
    521
    1
    end
    // Illustrated step by step
    gen str temp = string(yournum)  // make a string
    gen temp1 = substr(temp,1,1)  // pick off the first character
    gen digit1 = real(temp1)          // make it a number
    // Here's the whole thing in one line
    gen your1 = real(substr(string(yournum),1,1))
    list

    Comment


    • #3
      Oh I missed that! Thanks for the heads up!

      Comment

      Working...
      X