* Stata code
* Converts all values that equal missing such as -9999 to Stata missing values .
* Drops the program if it is already in the memory.
cap program drop recode_missing
* Defines a new program called recode_missing.
program define recode_missing
local variable_changed = 0
local variable_skipped_count = 0
local variable_skipped
* Loops through all variables identified by the first argument in the command.
foreach v of varlist `1' {
* Replaces the variable observations which match the second argument.
capture replace `v'=. if `v'==`2'
if _rc==0 local variable_changed = `variable_changed' + 1
if _rc!=0 {
local variable_skipped_count = `variable_skipped_count' + 1
local variable_skipped `variable_skipped' "`v'"
}
}
di "Recoded observations from `1' which equalled `2' into stata missing"
di "# of variables changed: `variable_changed' "
if `variable_skipped_count'!=0 {
di "# of variables skipped: `variable_skipped_count' "
di "skipped: `variable_skipped'"
}
end
* Example syntax
* . recode_missing * -9999
* This command will recode all variables that contain a -9999 into stata missing values ".".
***********************************************************
* example of the command in action *
use http://www.ats.ucla.edu/stat/stata/dae/logit.dta, clear
gen test="adsf"
* Does not make any logical sense to recode 0s as missing
recode_missing * 0
* Recoded observations from * which equaled 0 into stata missing
* # of variables changed: 4
* # of variables skipped: 1
* skipped: test
No comments:
Post a Comment