Recode the same value template for all variables in Stata
In my dataset, I have a bunch of Yes / No variables. For some reason "Yes" is encoded as 1 and "No" is encoded as 2 instead of 0. Now I want to recode 2 to 0 based on the value label "No".
How can I do this without having to check and recode each one?
There are some complications:
-
Each of these dummies has a value label sharing the dummy name name instead of sharing a "yesno" value label. So I can't just loop over all the variables labeled "yesno".
-
These dummies may have backup codes (-1 for Dont know, -2 for Refused, etc.). Due to these fallback codes, I believe that the best way to recode is to check the value label, because I know for sure that 2 is marked as No.
source to share
Suppose you are looking for variables with a value label attached. You can get these variables with ds
and pass your names to recode
.
. clear
. set obs 2
obs was 0, now 2
. forval j = 1/5 {
2. gen y`j' = _n
3. }
. label def yesno 1 yes 2 no
. label val y4 yesno
. label val y5 yesno
. ds, has(vall yesno)
y4 y5
. ret li
macros:
r(varlist) : "y4 y5"
. recode `r(varlist)' (2 = 0)
After that, the value label also needs to be configured:
. label def yesno 0 "No", modify
EDIT (following helpful notes from @Heisenberg)
If you use more than one set of value labels, you need to reapply this method for different value labels or, or consider a different one.
Here is a more general method for finding variables with values of 2 that are labeled as "None". Warning. This should change your dataset. Make sure you are an save
older version.
ds, has(vall)
foreach v in `r(varlist)' {
local lbl : label (`v') 2
if `"`lbl'"' == "No" {
replace `v' = 0 if `v' == 2
local label : value label `v'
label def `label' 0 "No", modify
}
}
source to share