Announcement

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

  • numeric values in a string

    I have a string variable "occupation" that records all values selected from a choice list. For example, when occupations 3 and 23 are selected, the occupation variable is "3 23".

    I want to merge two codes from the choice list together, and therefore replace all values where "2" is included as an occupation with "1". If "1" is already included as an occupation, I only want to remove "2".

    I use
    Code:
    gen has_2' = regexs(0) if(regexm(occupation "[2]"))
    to identify when a 2 is present but I am not sure how to only match "2"s when they are not 2s as a part of 20-9.


  • #2
    This is the problem solved by subinword().


    Code:
    * Example generated by -dataex-. For more info, type help dataex
    clear
    input str42 whatever
    "2 21 22"
    "9 2 3"  
    "1 2 3"
    end
    
    clonevar newvar = whatever 
    replace newvar = subinword(newvar, "2", "",  1) if strpos(" " + newvar + " ", " 1 ")
    replace newvar = subinword(newvar, "2", "1", 1)   
    
    list 
    
         +--------------------+
         | whatever    newvar |
         |--------------------|
      1. |  2 21 22   1 21 22 |
      2. |    9 2 3     9 1 3 |
      3. |    1 2 3      1  3 |
         +--------------------+

    Comment

    Working...
    X