Announcement

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

  • Replace while a condition is true for all observations

    I have a very simple problem: I have 2 string variables and I want each observation to be a string of length 10. If length is not 10 and the string is non-empty, I want to add as many leading zero's as necessary to reach length of 10. If the string is empty, I want to leave it as is.
    Here is my example data:

    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input str10(daughter_firm mother_firm)
    ""           "2837462784"
    "4392837632" "382764"    
    ""           "4920999936"
    "383746"     "28374"    
    ""           "93746"    
    "437263840"  ""          
    "384756224"  "384746304"
    end

    And here is what I tried:

    Code:
    local i=1
    foreach x of varlist mother_firm daughter_firm{
        replace `x'="" if `x'=="."
        g length`x'=length(`x') if length(`x')!=0
        egen mean_length`x'=mean(length`x')
        
        while (`i'){
            replace `x'="0"+`x' if length(`x')<10 & length(`x')>0
            drop mean_length`x'
            replace length`x'=length(`x') if length(`x')!=0
            egen mean_length`x'=mean(length`x')
            if mean_length`x'==10 {
                local i 0
            }
        }
    }
    Not only does it only work for the first variable, but I think I am making the code unnecessarily ugly and complicated.
    Would anyone have a suggestion to write simple and correct code?
    Last edited by Valentina Rutigliano; 01 Jun 2021, 12:48.

  • #2
    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input str10(daughter_firm mother_firm)
    ""           "2837462784"
    "4392837632" "382764"    
    ""           "4920999936"
    "383746"     "28374"     
    ""           "93746"     
    "437263840"  ""          
    "384756224"  "384746304" 
    end
    
    foreach var in daughter_firm mother_firm{
        replace `var'= substr("000000000", 1, 10-length(`var')) +`var' if inrange(length(`var'), 1, 9)
    }
    Res.:

    Code:
    . l, sep(0)
    
         +-------------------------+
         | daughter~m   mother_f~m |
         |-------------------------|
      1. |              2837462784 |
      2. | 4392837632   0000382764 |
      3. |              4920999936 |
      4. | 0000383746   0000028374 |
      5. |              0000093746 |
      6. | 0437263840              |
      7. | 0384756224   0384746304 |
         +-------------------------+

    Comment


    • #3
      Thanks Andrew... I knew there must be a much simpler way. I appreciate it!!

      Comment

      Working...
      X