-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmissing2zero.ado
68 lines (57 loc) · 1.68 KB
/
missing2zero.ado
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
program define missing2zero , rclass
version 14
syntax varlist [, substitute(string) mean bys(varlist)]
// Check for mixed-types in varlist
local rcSum = 0 // rcSum > 0 indicates at least one string variable
local rcProduct = 1 // rcProduct == 0 indicates at least one numeric variable
local byscount = 0
foreach var in `bys' {
local `byscount++'
}
foreach var in `varlist'{
capture confirm numeric variable `var'
local rcSum = `rcSum' + _rc
local rcProduct = `rcProduct'*_rc
}
if `rcSum' > 0 & `rcProduct' == 0{
di "Cannot mix numeric and string variables"
exit 109
}
if "`substitute'" != "" & "`mean'" == "mean" {
di as error "'substitute' cannot be combined with 'mean'"
exit
}
if `rcSum' > 0 & "`mean'" == "mean" {
di as error "'mean' is not defined for string variables"
exit
}
// Assign default values if none specified
if `rcSum' == 0 & "`substitute'" == ""{ // If numeric variables specified
local substitute = 0
}
else if `rcProduct' > 0 & "`substitute'" == "" { // If string variables specified
local substitute "NaN"
}
foreach var in `varlist'{
capture confirm numeric variable `var' // check type of variable
if _rc == 0 { // If numeric
if "`mean'" == "mean" { // if user wants to fill missing with mean value
tempvar vartemp
if `byscount' > 0 {
bys `bys': egen `vartemp' = mean(`var')
}
else {
egen `vartemp' = mean(`var')
}
qui replace `var' = `vartemp' if missing(`var')
drop `vartemp'
}
else { // if user wants to fill with zero or custom value
recode `var' (. = `substitute')
}
} // If string
else {
qui replace `var' = "`substitute'" if `var' == ""
}
}
end