*! 2.1.0 NJC 1 February 1999 STB-49 dm45.1 * 2.0.3 NJC & WWG 29 April 1997 program define destring version 6.0 syntax [varlist(default=none)] [ , noConvert noEncode Float ] if "`float'" == "" { local type "double" } else local type "float" if "`convert'"=="" & "`encode'"=="" { local todo 3 } else if "`convert'"=="" { local todo 1 } else if "`encode'" =="" { local todo 2 } if "`todo'" == "" { di in bl "nothing to do?" exit 198 } if "`varlist'"=="" { local 0 "_all" syntax varlist } else local expl "expl" tokenize "`varlist'" if "`expl'"!="" { local i 1 while "``i''" != "" { local oldtype : type ``i'' if substr("`oldtype'",1,3) != "str" { newline `err' di in red "``i'' not string" local err 109 } else { if `todo'==1 { ds1 tryit ``i'' `type' if "$S_1"!="" { newline `err' di in red "$S_1" local err 109 } } else if `todo'==2 { ds2 tryit ``i'' if "$S_1"!="" { newline `err' di in red "$S_1" local err 109 } } else if `todo'==3 { ds1 tryit ``i'' `type' local err1 "$S_1" if "`err1'"!="" { ds2 tryit ``i'' local err2 "$S_1" } else local err2 if "`err1'"!="" & "`err2'"!="" { newline `err' di in red "`err1'" di in red "`err2'" local err 109 } } } local i = `i' + 1 } if "`err'"!="" { exit `err' } } local i 1 while "``i''"!="" { local oldtype : type ``i'' if substr("`oldtype'",1,3)=="str" { if `todo'==1 | `todo'==3 { ds1 doit ``i'' `type' local enc "converted to " } if ("$S_1"!="" & `todo'==3) | `todo'==2 { ds2 doit ``i'' local enc "encoded into " } local newtype : type ``i'' if "`newtype'" != "`oldtype'" { di in gr "``i'' was " in ye "`oldtype'" /* */ in gr " now `enc'" in ye "`newtype'" } } local i = `i' + 1 } end program define ds1 /* {doit|tryit} */ args todo v t global S_1 capture assert real(`v')!=. if trim(`v')!="" & trim(`v')!="." if _rc { global S_1 /* */ "`v' contains values that cannot be converted to numeric" exit } if "`todo'"=="tryit" { exit } tempvar copy quietly { gen `t' `copy' = real(`v') compress `copy' local varl : variable label `v' label var `copy' "`varl'" move `copy' `v' nobreak { drop `v' rename `copy' `v' } } end program define ds2 /* {doit|tryit} */ args todo v global S_1 capture assert real(`v')==. if _rc { global S_1 "`v' contains some numeric values" exit } tempvar len quietly { capture assert `v'==trim(`v') if _rc { tempvar vt gen str1 `vt' = "" replace `vt' = trim(`v') } else local vt "`v'" capture encode `vt', gen(`len') label(`v') if _rc { if _rc==134 { global S_1 /* */ "`v' contains too many values to encode" exit } error `rc' } if "`todo'"=="tryit" { exit } qui compress `len' local lbl : variable label `v' label var `len' "`lbl'" move `len' `v' nobreak { drop `v' rename `len' `v' } } end program define newline /* [anything] */ if "`1'"!="" { di } end