Use value label in if command

梦想与她 提交于 2019-12-19 02:18:09

问题


I am working with a set of dta files representing surveys from different years.

Conveniently, each year uses different values for the country variable, so I am trying to set the country value labels for each year to match. I am having trouble comparing value labels though.

So far, I have come up with the following code:

replace country=1 if countryO=="Japan"
replace country=2 if countryO=="South Korea" | countryO=="Korea"
replace country=3 if countryO=="China"
replace country=4 if countryO=="Malaysia"

However, this doesn't work because "Japan" is the value label, not the actual value.

How do I tell Stata that I am comparing the value label?


回答1:


Try

replace country=1 if countryO=="Japan":country0valuelabel
replace country=2 if inlist(countryO,"South Korea":country0valuelabel,"Korea":country0valuelabel)

You will have to replace country0valuelabel with the corresponding value label name in your data. You can find out its name by looking at the penultimate column in the output of describe country0.




回答2:


To complement @Dimitriy's answer:

clear all
set more off

sysuse auto
keep foreign weight

describe foreign
label list origin

replace weight = . if foreign == 0

list in 1/15
list in 1/15, nolabel 

describe displays the value label associated with a variable. label list can show the content of a particular value label.




回答3:


I know I'm responding to this post years later, but I wanted to provide a solution that will work for multiple variables in case anybody comes across this.

My task was similar, except that I had to recode every variable that had a "Refused" response as a numerical value (8, 9, 99, etc) to the missing value type (., .r, .b, etc). All the variables had "Refused" coded a different value based on the value label, e.g. some variables had "Refused" coded as 9, while others had it as 99, or 8.

Version Information Stata 15.1

Code

    foreach v of varlist * {        
        if `"`: val label `v''"' == "yndkr" {
          recode `v' (9 = .r)
        }

        else if `"`: val label `v''"' == "bw3" {
          recode `v' (9 = .r)
        }

        else if `"`: val label `v''"' == "def_some" {
          recode `v' (9 = .r)
        }

        else if `"`: val label `v''"' == "difficulty5" {
          recode `v' (9 = .r)
        }               
    }

You can keep adding as many else if commands as needed. I only showed a chunk of my entire loop, but I hope this demonstrates what needs to be done. If you need to find the name of your value labels, use the command labelbook and it will print them all for you.



来源:https://stackoverflow.com/questions/22767838/use-value-label-in-if-command

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!