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:
And here is what I tried:
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?
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 } } }
Would anyone have a suggestion to write simple and correct code?
Comment