Announcement

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

  • separate number (string variable) in digits

    Hello,

    I need some help please. I have a string variable which is a number, each digit of the number has a meaning and I need to seperate the digits.
    But not all numbers contain the same number of digits..
    I just need the first digits of the number.
    Do you have an idea how I can seperate the number?

    Thanks in advance
    Lisa

  • #2
    Absent an example of your data, here is a sandbox and some technique:

    Code:
    clear 
    set obs 5 
    gen mystrvar = substr("a1c2e", 1, _n) 
    list 
    forval j = 1/5 { 
        gen char`j' = substr(mystrvar, `j', 1) 
    } 
    list
    which gives

    Code:
    . clear 
    
    . set obs 5 
    obs was 0, now 5
    
    . gen mystrvar = substr("a1c2e", 1, _n) 
    
    . list 
    
         +----------+
         | mystrvar |
         |----------|
      1. |        a |
      2. |       a1 |
      3. |      a1c |
      4. |     a1c2 |
      5. |    a1c2e |
         +----------+
    
    . forval j = 1/5 { 
      2.     gen char`j' = substr(mystrvar, `j', 1) 
      3. } 
    (1 missing value generated)
    (2 missing values generated)
    (3 missing values generated)
    (4 missing values generated)
    
    . list 
    
         +--------------------------------------------------+
         | mystrvar   char1   char2   char3   char4   char5 |
         |--------------------------------------------------|
      1. |        a       a                                 |
      2. |       a1       a       1                         |
      3. |      a1c       a       1       c                 |
      4. |     a1c2       a       1       c       2         |
      5. |    a1c2e       a       1       c       2       e |
         +--------------------------------------------------+
    Once past the first session, users need to know about the basic functions. One tutorial is at

    http://www.stata-journal.com/article...article=dm0058

    Comment


    • #3
      hello nick,
      thanks for your help and also for your paper.
      just one more question, is it easier to seperate the digits if I do not have a string variable?
      how does it work in this case?
      sorry for this kind of basic questions, but for me it is really dificult to work with stata..

      Comment


      • #4
        No. With a numeric variable it is not easier. It is easier to work on the string equivalent.

        Comment

        Working...
        X