0
votes

I am using the code below to generate a new variable in Stata but got an error stating "hv2 invalid name r(198);"*

gen ph= hv1==2 
replace ph=. if hv2*!=1
label values ph yesno
label var ph "PH present"

where hv2* refers to variables from hv2_1 to hv2_98 (98 variables in all). hv2* are household variables and values not 1 indicate that respondents are not from the households used in the survey. My new variable ph is conditioned on whether respondents are residents in the households used in the survey or not. Non-residents should be missing in the new variable (ph) hence "replace ph=. if hv2!=1". That is cases with any value not 1 in the hv2 variables should be missing in the new variable.

1

1 Answers

1
votes
gen ph = hv1 == 2 
quietly forval j = 1/98 { 
    replace ph = . if hv2_`j' == 1
} 

The command egen offers functions that could be used here, so that (for example)

gen ph = hv1 == 2 
egen any1 = anymatch(hv2_*), values(1) 
replace ph = . if any1 

may seem to avoid the loop, but you just have a loop inside the code for anymatch() to do the same thing.