Announcement

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

  • extract strings from a numeric variable

    I have an id variable that looks like this:

    id
    001410AP00
    001410BP03
    001570CP03
    071950AP00
    083950CP05
    107590AP00

    It is a string variable. I need to convert to a numeric variable that drops the AP, BP or CP. For example, the new variable should look like this:

    id_new
    00141000
    00141003
    00157003
    07195000
    08395005
    10759000

    Any idea how I can do this?




  • #2
    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input str10 id
    "001410AP00"
    "001410BP03"
    "001570CP03"
    "071950AP00"
    "083950CP05"
    "107590AP00"
    end
    
    gen wanted= ustrregexra(id, "[^\d]", "")
    Res.:

    Code:
    . l, sep(0)
    
         +-----------------------+
         |         id     wanted |
         |-----------------------|
      1. | 001410AP00   00141000 |
      2. | 001410BP03   00141003 |
      3. | 001570CP03   00157003 |
      4. | 071950AP00   07195000 |
      5. | 083950CP05   08395005 |
      6. | 107590AP00   10759000 |
         +-----------------------+

    Comment


    • #3
      Thank you Andrew! This worked!

      Comment


      • #4
        Here's another way to do it.

        Code:
        clear 
        input str10 id
        001410AP00
        001410BP03
        001570CP03
        071950AP00
        083950CP05
        107590AP00
        end 
        
        gen newid = substr(id, 1, 6) + "00" + substr(id, 9, 2)
        
        list, sep(0)
        
             +-------------------------+
             |         id        newid |
             |-------------------------|
          1. | 001410AP00   0014100000 |
          2. | 001410BP03   0014100003 |
          3. | 001570CP03   0015700003 |
          4. | 071950AP00   0719500000 |
          5. | 083950CP05   0839500005 |
          6. | 107590AP00   1075900000 |
             +-------------------------+

        Comment

        Working...
        X